0

I am implementing a React component to make payments. And there is a part in my code where I used useEffect to setValues from useState. The Code is as follows:

React.useEffect(()=>{
  axiosFetch
    .get("auth/get_user")
    .then(res => {
      setUserName(res.data.name);
      setUserEmail(res.data.email);
      setUserContact(res.data.contact);
      console.log(res);
      console.log(userName);
      console.log(userEmail);
      console.log(userContact);
    })
    .catch(() => {})
  }, [])

When I run this code the browser prints console.log(res) as expected. But it prints the other three statements as Empty Strings (I expect some other values).

Here is what the console prints.

enter image description here

As you can see that console.log(res) is printing correctly. Then why not the other three??

skyboyer
  • 22,209
  • 7
  • 57
  • 64
  • 1
    Does this answer your question? [useState set method not reflecting change immediately](https://stackoverflow.com/questions/54069253/usestate-set-method-not-reflecting-change-immediately) – Sinan Yaman Apr 06 '21 at 11:14
  • Because setState is an async call, it will not apply immediately. – hackape Apr 06 '21 at 11:14
  • can I write it as userName = res.data.name ? What are the demerits of doing so? – Paras Bansal Apr 06 '21 at 11:20
  • @ParasBansal - That's just not how React works. I recommend going through some of the tutorials and documentation on https://reactjs.org/. – T.J. Crowder Apr 06 '21 at 11:29

1 Answers1

0

The state is set asynchronously.

The variables won't have new values until the component is re rendered.

Setting them will trigger a rerender, but the useEffect callback (where you are logging the values) won't run again because none of its dependencies have changed.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335