I have context in my react-app, I want to call a query in context and set the state value to an object from the api data. I have tried the following and I get the error, can't read property of undefined (4). So I know this could be because the data has not yet been returned and therefore I can't set the state to the object in the array, so how to get around this? Also how would I handle the status i.e loading etc in the component the context is passed to.
Another question is should I be calling the API in context, or should I call in the component and then set the context state in the component? is that better approach?
Code so far:
export const DataProvider: React.FunctionComponent = ({ children }) => {
const getApi = async (): Promise<any> => {
const response = await axios.get(`https://www.xxxxxx`).then(res => res.data);
return response;
}
const { data: result, status, error, isFetching }: any = useQuery(['apiData'], () => getApi());
const [myValue, setmyValue] = React.useState(result[4]); // this is causing the issue
return (
<DataContext.Provider value={{myValue, setmyValue, result}}>
{children}
</DataContext.Provider>
);
};