I'm unsure how to handle errors in a redux reducer. When my API fetch returns data, I need to transform its structure and check various properties have been set on the resulting data. However, I cannot throw errors in the reducer as redux requires at least the previous state to be returned. How do I go about handling this?
Note: I'm using react-redux-toastr to handle errors, and have access to the error dispatcher in the component and action functions.
reducers/object-search.js:
case "FETCH_OBJECTS_FULFILLED": {
// munge data into expected format
const _allObjects = [];
const data = action.payload;
// if can't find the surveys property
if (!data.hasOwnProperty("surveys")) {
// - - How do I handle this within the reducer? - -
// this.handleAlert("error", "ERROR", " Cannot find a list of surveys. Please contact support.");
return {
...state,
fetching: false
}
}
// transform data (omitted for brevity's sake)
return {
...state,
fetching: false,
fetched: true,
options: _allObjects,
surveys: data.surveys.map(survey => survey.name)
// toastrs: [newToastr, ...state.toastrs]
};
}
I did attempt to update the toastr's slice of the store in the ObjectSearch reducer after connecting in the ObjectSearch Component:
reducers/index.js:
const rootReducer = combineReducers({
toastr: toastrReducer,
ObjectSearch
});
components/object-search.js
@connect(store => {
return {
fetching: store.ObjectSearch.fetching,
fetched: store.ObjectSearch.fetched,
ready: store.ObjectSearch.ready,
surveys: store.ObjectSearch.surveys,
toastrs: store.toastr.toastrs
};
})
however, adding the following to reducers/object-search.js: seems to update ObjectSearch.toastrs rather than toastr.toastrs :(
const toastrs = [...state.toastr];
const newToastr = {
id: guid(),
type: 'light',
title: 'OBJECT SEARCH ERROR',
message: 'No Data. Please contact support.',
options: {
...REDUX_TOASTR_OPTIONS,
icon: icons.ERROR_ICON,
status: 'error'
}
};
toastrs.push(newToastr);
I'm a react/redux newbie, so any help on app structure here would be appreciated!