Arasto
Arasto

Reputation: 491

Lifecycle issue using React Hooks

My user State

const [user, setUser] = useState({});

Fetch Function

    async function checkIfUserIsEnabled() {
        let URL = `http://localhost:8080/users/finduserbytoken?id=`;
        const res = await fetch(URL);
        res.json()
           .then(res => setUser(res))
           .catch(err => setErrors(err));
      }

useEffect(calling the fetch method, checkIfUserIsEnabled)

    useEffect(() => {
        verifyEmail(getTokenIdFromURL);
        checkIfUserIsEnabled();
        return () => {
            /* */
        };
    }, []);

Return

    return (
        <div className="emailVerificationWrapper">
        {user.enabled ? <h1>Result is true!</h1> : <h1>Result is false</h1>}
        </div>
    )




My Issue: is that the return method is called before the state causing the user.enabled to always be false, even though the setUser, which is called in the useEffect updated the state of user.enabled to true.

How can i make the state update before getting to the render?

Upvotes: 2

Views: 58

Answers (1)

Eslam Abu Hugair
Eslam Abu Hugair

Reputation: 1208

first of all, you are calling async functions which will not be executed on the same order on the useEffect, so I propose you clean the functions a bit like:

const checkIfUserIsEnabled = (user) => {
  if (user)
    setUser({ enabled: true, ...user })
}
const getUser = () => {
  let URL = `http://localhost:8080/users/finduserbytoken?id=`;
  const res = await fetch(URL);
  const user = res.json()
  checkIfUserIsEnabled(user)
}


useEffect(() => {
  verifyEmail(getTokenIdFromURL)
    .then(verified => {
      getUser()
    })
}, []);


  return (
        <div className="emailVerificationWrapper">
           <h1>{` Result is ${user.enabled}`}</h1>
           <br/>
           <div>Current User State:</div>
           <pre>{JSON.stringify(usre)}</pre>
        </div>
    )

now it's easier for you to debug and cleaner to read

Upvotes: 1

Related Questions