I am trying to fetch some data from the API and setting the data in my redux store. However, when I try to do some operation with the data from the redux store that variable is empty. I have used await but it seems it does not work. However, after useEffect the redux store(api data) data is visible and can do operations on it. Any help is appreciated. Please note I need to access the redux store field not just get the returned data from the function. Accessing the redux store field is important. Here is my code:
useEffect(() => {
async function loadData() {
const startingDateYear = moment();
const eventDates = generateDatesForYear(startingDateYear.year().toString());
await dispatch(fetchData('0009', eventDates[0], eventDates[1]));
}
loadData();
console.log(event.myDataArray) // event is a reducer and myDataArray is the field. It can be accessed outside the function with data incorporated but within useEffect I am not able to use the freshly fetched data.
return {};
}, []);
export const fetchData = (p1, p2, p3) => {
return async dispatch => {
const path = `dataFromAPIURL`;
try {
dispatch({
type: FETCH_STARTED,
});
const myDataArray = await RestService.get(path);
dispatch({
type: FETCH_FINISHED,
});
dispatch({
type: UPDATE_REDUCER_STATE,
payload: myDataArray,
});
return myDataArray;
} catch (error) {
// TODO: error handling
dispatch({ type: FETCH_ERROR, payload: error });
}
};
};