I'm trying the fetch data from a json API and setting it to a state. Currently using visual studio code with a pixel 4 emulator.
When I try to update my state inside of a useEffect method on the emulator's first launch or on reload, it doesn't change. If I save in vs code, the data in state updates as intended.
...
import React, {useState, useEffect} from 'react';
import {getJsonData} from './getJsonData';
const myApp = () => {
const [state, setState] = useState({
isLoading: true,
data: null,
});
const updateState = data => {
console.log(data); //Logs the correct Json data everytime
setState(state => ({...state, isLoading: false, data: data}));
console.log(state.isLoading); //Doesn't update on reload (updates only on save)
console.log(state.data); //Same as above
};
useEffect(() => {
getJsonData().then(data => updateState(data));
}, []);
return (
<View>
<Text>{state.data.title}</Text>
<Text>{data.data.completed}</Text>
</View>
);
}
And this is the getJsonData( ) function:
export async function getJsonData() {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
let responseJson = await response.json();
return responseJson;
} catch (error) {
console.error(error);
}
}
I ultimately want the state to update on the application's first run, on reload, as well as each time I call a certain reloadApp( ) function.
If the above code is not the best practice, please don't hold back to correct me as I'm just learning about states.