Home > Enterprise >  useEffect is continually re-rendering when setting state
useEffect is continually re-rendering when setting state

Time:10-19

In my useEffect function, I'm first attempting to verify my 'auth' token using an axios call. After that, I then look to set state based upon the response I get from data either provided by the BE or stored in localStorage. Finally, I'm then attempting to console.log the state so that I can make sure the state is updated (which it is).

However, it's just continually re-rendering at the moment and not just loading once.

Note - I'm not displaying any of this information on the page itself, this is simply a processing screen used to complete some BE calls.

Here's my useEffect function:

useEffect(() => {

    axios.post("/api/verifyToken", {
        token: JSON.parse(localStorage.getItem('auth'))
    })
    .then((response) => {
        setUserId(response.data)
        setName(localStorage.getItem('name'))
    }).then(() => {
        console.log("Testing here..")
        console.log(userId)
        console.log(name)
    })

    }, [userId, name])

CodePudding user response:

you need to remove userId and name from the dependency of effect (the [userId, name] parameter)

if you need to print out the result to console you may

  • print out the result from response of the promise instead of state
  • create another effect to print the userId and name
useEffect(() => { /** your HTTP request and set result to state */ },[])

useEffect(() => console.log(userId, name), [userId, name])
  • Related