Home > front end >  why setState(data) in fetch function doesn't work unless I update the page
why setState(data) in fetch function doesn't work unless I update the page

Time:12-09

Hello I have a list of things and when I click on one of them I want to render the detail page. So in the list I added the link to "/:id" and this is the code on the detail component:

`

 const [cavallo, setCavallo] = useState({})

 const {idCavallo} = useParams()


let getCavallo = async () => {
    try {
        let response = await fetch(`http://localhost:5001/cavalli/${idCavallo}`)
        if(response.ok) {
            let data = await response.json();
             setCavallo(data)
             console.log(cavallo)
       
        } else {
            console.log("something went wrong")
        }
       
    } catch (error) {
        console.log(error)
    }
}

     useEffect(() => {
   
    getCavallo()
    console.log(cavallo)
     }, []);

`

the console.log(cavallo) after setCavallo(data) shows me an empty object, but if I change something in the file and save again it show the propers object and renders the page. I understand it has something to do with the mounting but I don't know where is the problem

CodePudding user response:

setState will update the state by next render, modify like this:

useEffect(() => {
    getCavallo()
}, []);

useEffect(() => {
    console.log(cavallo)
}, [cavallo]);
  • Related