-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>
</>
)
} ```
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.
– MarceloCP
one of the possible answers would be that before the
React
call the functionsetState
, is doing theconsole.log
where you are printing an empty object which is the initial state. You could change thisconsole.log
for the jobbuscarUser
, right after the request is completed. After a read in the React Event Cycle: https://reactjs.org/docs/react-component.html– augusto1997