I am building an app. This app needs to request a woocommerce API for product data. The API will only allow 100 items at a time, so I have had to call this request 4 times with dynamic page parameters.
My aim for this data is to have a reducer combine the data into one array that can be filtered in a react component.
My problem at the moment is that my reducer is adding each API call to state in its own array. So rather than have a big array with 300 ish products in, I have 1 array that contains 4 arrays each with 100 products in. Please see the image below.
Here is the action:
export function fetchJuiceData(page) {
return dispatch => {
dispatch(getDataPending("juicedata"));
return axios
.get(
"API_call/end_point/&page=" +
page
)
.then(response => {
dispatch(getDataSuccess("juicedata", response));
})
.catch(err => {
dispatch(getDataFailure("juicedata", err));
});
};
}
Which gets run 4 times with async:
const juiceDataPages = 4;
var i;
for (i = 0; i < juiceDataPages; i++) {
await dispatch(fetchJuiceData(i + 1));
}
My reducer:
const juiceDataReducer = (state = initState, action) => {
switch (action.type) {
case "FETCH_JUICEDATA_PENDING": {
return { ...state, fetching: true };
}
case "FETCH_JUICEDATA_REJECTED": {
return { ...state, fetching: false, error: action.payload };
}
case "FETCH_JUICEDATA_FULFILLED": {
return {
...state,
fetching: false,
fetched: true,
juiceData: [...state.juiceData, action.payload]
};
}
default: {
return state;
}
}
};
I am not the greatest coder in the world and would love your input. I have been banging my head against a wall for days now. TIA.