ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Monday, December 12, 2022

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

 December 12, 2022     react-hooks, reactjs   

Issue

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


Solution

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

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

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


Answered By - rszf
Answer Checked By - - Terry (ReactFix Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix