Home > Mobile >  Next.js React.js doesn't renders useState that I'm getting in useEffect
Next.js React.js doesn't renders useState that I'm getting in useEffect

Time:11-11

I'm getting Array of objects inside useEffect: enter image description here

Then I'm trying to map it and render: enter image description here

And I'm getting the result that it doesn't render it. Firstly it get's an empty Array as default and when State changes in useEffect it doesn't rerender it. Why and how to solve it? (Next.js React.js maybe some troubles with next? )

CodePudding user response:

Just a quick tip, it'd be more helpful to actually use "Code" here to paste your code than to screenshot an image.

Anyway, try setting up your useEffect to first check for the token, then run the code with the [token] dependency. So your useEffect should start with:

if(!token) { //you're checking if token is already set, so you don't get into a loop
//your code here
}, [token] //you want your component to re-render in case of a token change, which will happen only on first setToken because you're checking if token is already set above.

CodePudding user response:

You just need to add the tokens to your useEffet deps.

useEffect(()=>{
    //using tokens or whatever
}, [tokens])

You'll also don't want infinite loop state changing so you'll need to add a condition of setTokens and that condition would be:

useEffect(()=>{
    if (tokens.length === 0) {
        //do whatever you want
        setTokens(newTokens);
    }
}, [tokens])
  • Related