0

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])
1
  • 1
    useEffect has a dependency on userId and name, which you set in the function passed to it, causing it to run the function again, which updates userId and `name, etc. Commented Oct 18, 2022 at 15:48

1 Answer 1

2

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])
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.