useState does not update

Asked

Viewed 227 times

-1

I have a function that fetches user information in an API and stores it in a useState, would like to know if I put a console.log to see if stored the data correctly in useState returns me empty but on the screen shows me the values only from the second request is shown the information in the console, I will post the code here:



export default function Teste() {

  const [repositories, setRepositories] = useState({});
  const [nome, setNome] = useState()

  const handleChange = (event) => {
    const auxValues = { ...nome }
    auxValues[event.target.name] = event.target.value
    setNome(auxValues)
  }

  function buscarUser(cpf){
    fetch(`http://localhost:8080/rest/v1/user/${cpf}`)
      .then(res => res.json())
      .then(data => setRepositories(data));
  }

  function handleUser(){
    buscarUser(nome.usuario)
    console.log(repositories)
  }

  return(
    <>
      <input name="usuario" onChange={handleChange}></input>
      <button onClick={ handleUser }>Buscar User</button>
      <label> {repositories.nome} </label>
    </>
  ) 
} ``` 

1 answer

0

I recommend taking a look at promises and also a little about programação assíncrona in the Javascript, explaining in a general way, what is happening there is that in its function handleUser, you are running a buscarUser in which is a promise and it is not being expected the end of its execution to carry out the console.log, a simple way to solve this would be to simply put:

function handleUser(){
    buscarUser(nome.usuario)
     .then(() => console.log(repositories))
 }

Thus the console.log will only be executed when the request ends and is successful. I hope you helped ! Hugs !

  • I changed the function according to your suggestion, but in the log the empty object keeps appearing but html code appears the good data, finally I have already put the functions as async even so without success. Anyway as this rendering of good in html is not "for now " interfering in the system, but just wanted to understand the pq this happens. But thanks for the suggestion and help.

  • one of the possible answers would be that before the React call the function setState, is doing the console.log where you are printing an empty object which is the initial state. You could change this console.log for the job buscarUser, right after the request is completed. After a read in the React Event Cycle: https://reactjs.org/docs/react-component.html

Browser other questions tagged

You are not signed in. Login or sign up in order to post.