Home > Net >  React Hook UseEffect create duplicate objects in setState
React Hook UseEffect create duplicate objects in setState

Time:07-29

I got a problem with a component. I make a n number calls to an external API and then get back values inside an object. I want to add each of this object return in the state. However, each object is duplicate in my state. I try to put conditions but nothing work. I just started with React and Node so I'm sorry if the solution is obvious...


    //Id for the API calls
    const Ref = ['268', '294']
 
    const nbreLiens = Ref.length
    
    //For each Id we make an API call, get the response, and set the state without erasing the previous value
    Ref.map(lien=>{

      const Tok = localStorage.getItem('token');

      Axios.get("http://localhost:3001/liens/sup/" Tok "/" lien).then((Response) => {
        
        //We shouldn't get more entries that the number of Id's
        if (test.length<nbreLiens){
          setTest(test=>[...test,Response.data])
        }
      })
    })

  }, [])

CodePudding user response:

Try resolving all the API call Promises first, then add the resposes to the state.

(Im not handling errors)

//Id for the API calls
const Ref = ['268', '294']

useEffect(() => {
    const getElements = async (idsToGet) => {
        const Tok = localStorage.getItem('token');
        const allPromises = idsToGet.map(id => Axios.get("http://localhost:3001/liens/sup/"   Tok   "/"   id))
        const dataElements = await Promise.all(allPromises)
        const responseDataElements = dataElements.map(response => response.data)
        setTest(() => responseDataElements)
    }
    getElements(Ref);
}, [])

CodePudding user response:

Seems to me that your statement if (test.length<nbreLiens){ will not work as you are expecting.

In resume: test.length will always be the same even after calling setTest inside this function.

From react docs:

In React, both this.props and this.state represent the rendered values, i.e. what’s currently on the screen.

Calls to setState are asynchronous - don’t rely on this.state to reflect the new value immediately after calling setState. Pass an updater function instead of an object if you need to compute values based on the current state (see below for details).

You can read more about this at: https://reactjs.org/docs/faq-state.html

  • Related