Skip to content
Advertisement

Fetching data in react returns “undefined” at first time

I have a function component that I control user login with react. According to the username and password entered in the input, if the value returned from the API is true, it redirects to another page, if false, it stays on the same page. When I press the button when the username and password are correct, the first value is It returns undifined , but when I press the button for the second time, it returns true and redirects to another page.

console.log(isUser); // When I check, it shows undefined even though the values ​​for the first name and password are full, but when I press the button again, it returns true if the username and password are correct.

What is the reason of this?

JavaScript

Advertisement

Answer

userService.getUserControl is async operation. To be able to use this response you should wrap your code in then() callback. But setting the state value using useState is also async operation and there is no guarantee that you will be able to read the actual value right after calling setUser. You could do something like that:

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement