Reputation: 97
I'm extremely new to React.js. I am trying to change a variable recepies
which is in state using hooks. Below is my code snippet:
import React, { useState, useEffect } from 'react';
import './App.css';
function App() {
const [recepies, setRecepies] = useState([]);
useEffect(()=>{getRecepies()}, []);
//const example = Some valid API URL
const getRecepies = async () =>{
const response = await fetch(example);
const data = await response.json();
//data.hits is an array of 10 objects
setRecepies(data.hits);
console.log(recepies);
// prints nothing
}
return (
<div className="App">
</div>
);
}
export default App;
The problem is that setRecepies
is NOT updating the recepies
state. Why is that?data.hits
is a valid array that has 10 objects that I'm fetching using an API.
Upvotes: 0
Views: 444
Reputation: 85002
recepies
is a local const
. It will never change, and that's not what setRecepies
is trying to do. Putting a log statement where you've put it can only ever log out what recepies
was equal to when getRecepies
was created.
The purposes of setRecepies
is to tell react to rerender the component. When that second render happens, a new local const
will be created which will get the new value. This variable is visible to anything created on that second render, not to things created on the first render. So if you want to see the new value, put your log statement in the body of the component so you can see what value it's rerendering with.
const [recepies, setRecepies] = useState([]);
console.log('rendering with', recepies);
Upvotes: 1