Skip to content Skip to sidebar Skip to footer

How Do I Fetch Only Once?

I want to fetch a name and a photo from a rest API called 'randomuserAPI', to add to some kind of card in my website, but it just keeps fetching again and again in a loop, and neve

Solution 1:

Issue :

render -> getUser -> setting State -> re-render -> getUser .....
const Course = ({author}) => { 

    const [userInfo, changeUserInfo] = useState('User')
    const [userPhoto, changeUserPhoto] = useState('https://i.stack.imgur.com/l60Hf.png')

    //------------- ISSUE -------------
    // `getUser` get called when ever component get rendered
    // and it is setting up state , so it is causing re-rendering
    // so it's kind of infinte loop 
    // render -> getUser -> setState -> re-render .....
    getUser(changeUserInfo, changeUserPhoto)'

    return(
        <div className="course">
            <h4>{userInfo}</h4>
            <p>{author}</p>
            <img src={userPhoto} width="200px" height="200px" alt=""></img>
        </div>
    );
}

Solution :

You can put getUser inside useEffect : so it will get called only when component get mounts

useEffect(() => {
    getUser(changeUserInfo, changeUserPhoto)
},[]);

Solution 2:

getUser without any restriction will cause an infinity loop (component Course render > call getUser > change userInfo and userPhoto > trigger render Course > call getUser again > ...)

You have to put your function that cause side effect (fetch API) into useEffect hook, in this context is getUser(changeUserInfo, changeUserPhoto) function.

useEffect = (() => {
   getUser(changeUserInfo, changeUserPhoto)
}, [])

The empty array is make sure getUser function just run only once time.

You should read more about useEffect hook


Solution 3:

Your concerns as far as I understood are:
You want a single result from the API. You need the result to be constant and must not change.

Instead of using https://randomuser.me/api?results=3 use https://randomuser.me/api?results=1 You were fetching 3 results and expecting a single result.

To make the result constant you need to store the fetched result in database and check the data exist or not before fetching. You only need to fetch data if its not exist in your database.


Post a Comment for "How Do I Fetch Only Once?"