Attempting to update state after data load on useEffect. Able to update a local variable but not state. I am following an example from https://www.robinwieruch.de/react-hooks-fetch-data/ where Robin sets state in a similar way. For some reason, the state variable is never set correctly in my case.
Using AWS Amplify to load graphQL data. Seems to work successfully for local variable but not state variable.
const [serviceTypes, setServiceTypes] = useState([{}]);
let myServiceTypes = [{}]; // try it with a local variable to debug
useEffect(() => {
let unmounted = false;
async function fetchData() {
const result = await API.graphql(
graphqlOperation(queries.listServiceTypes)
);
console.log(result);
console.log('setting service types...');
console.log(result.data.listServiceTypes.items);
setServiceTypes(result.data.listServiceTypes.items);
myServiceTypes = result.data.listServiceTypes.items;
console.log(myServiceTypes); // set correctly
console.log(serviceTypes); // empty
}
if (!unmounted) {
fetchData();
}
return () => {
unmounted = true;
};
}, []);
Expecting serviceTypes to be set to the data loaded. Instead it is empty.