What this function in my react code intends to do is send the data via post to an API and collect the result. To do the tests, the correct data I have is email [email protected] with password 1234
handleSubmitLogin = (e) => {
e.preventDefault();
const requestOptions = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email: '[email protected]' , password: '1234123' })
};
fetch('http://localhost:8000/api/login', requestOptions)
.then(response => response.json())
.then(result => console.log(result) );
};
Result with incorrect login
What I don't know how to do inside the fetch instruction is to save the result in a state, for example how to set this.state.userId with the user.id that the fetch returns.
And in case an incorrect access is returned, set another state such as this.state.userLogged with False value.
How to use useState
It can be thought of
react state
as a black box that persists changes of state variables. This box entity is in another memory space, but the component communicates with it viauseState
;Also, to modify the value of the state the set function is used
setUserInfo
, the black box can be updated.However, in order to get the current value of the content of said black box, you have to re-render the component, since the component and the black box are not synchronized , but communicate asynchronously:
The method
setUserInfo
updates the stateuserInfo
in the black box, to later re-render the component, with this the last value of the state can be readuserInfo
, since this state variable will receive asynchronously, the current value of the black box in each re -render:field notes
API calls create side effects, I suggest reading more about useEffect .
Regarding the state handling for the error, I suggest to follow the same logic but this time, communicate with su
setState
from the fetch->catch function