Reputation: 776
Ok so I feel like I am just missing something very obvious here and I have been trying to work through it on my own for a couple hours now to no avail. I'm creating an app with React Native and in my main App.js file I am doing this (for brevity's sake assume that I am requiring in all that is necessary) --
const App = () => {
let [fontsLoaded] = useFonts({
DoHyeon_400Regular,
});
const [state, setState] = useState({});
useEffect(() => {
async function test(){
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1')
.then(response => response.json())
.then(json => {
setState(json)
console.log(state)
})
}
test()
}, [])
return(
<View>
// some component(s)
</View>
)
}
From what I have read in the docs and a few other SO posts I have checked I do not see why this does not work. Version of React is > 16.8 so that should not be the issue. If I log out json var it displays the proper response from the API call.
Upvotes: 0
Views: 89
Reputation: 76
setState
is not synchronous. If you immediately log the state, you will not notice the update.
Also, if you use the await
keyword, you don’t have to use then
anymore.
Upvotes: 1
Reputation: 84912
state
is a local const. It will never change, and that's not what setState
is trying to do. Instead, calling setState tells react to rerender the component. When that rerender occurs, a new local variable is created with the new value.
So everything's working, except that your console.log is in a spot where it's not particularly useful. If you want to see that the component has rerendered with the new value, move the log statement to the body of the component.
const [state, setState] = useState({});
console.log("rendering with", state);
useEffect(() => {
async function test(){
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let json = await response.json();
setState(json);
}
test()
}, [])
Upvotes: 4