I have an issue with data not being available in the app that is returned from an API when my component is being rendered. I am using the async await syntax on the API call, but missing something essential as it errors out.
I'm using Axios to make the API call, and Axios-Mock-Adapter to create a mock response.
Simplified example of the code:
App.js
const [data, setData] = useState();
const MainContext = createContext({
data: {},
});
useEffect(() => {
const getPosts = async () => {
const response = await axios.get(
"/mockedEndpoint"
);
setData(response.data);
};
getPosts();
}, []);
return (
<MainContext.Provider value={data}>
<MyComponent />
</MainContext.Provider>
);
MyComponent.jsx
const data = useContext(MainContext);
console.log("data", data); // first prints empty object, then a second later with correct data
console.log("data", data.user); // if I have this line, it throws an error (user does exist a second later)
Am I missing something obvious? Do I need to handle the data in MyComponent.jsx differently? I imagined that having the getPosts be an async function would let me access the returned values from the API in my component.