Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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)
     }, []);

`

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

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

useEffect(() => {
    console.log(cavallo)
}, [cavallo]);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading