Sam Sam - 3 years ago 49
React JSX Question

Trying to save data in localStorage

In my React app, after fetching some data from the API, I'm trying to store the data in localStorage as well as my redux store. I keep getting the


Error: Actions must be plain objects. Use custom middleware for async
actions.


Here's my code:

export const setDataInStore = (myData) => {

return {
type: types.SET_MY_DATA,
myData
};
}

const setDataInLocalStorage = (myData) => {

window.localStorage.myData = myData;
}

export const getMyData = () => {

return (dispatch) => fetch('/api/mydata', fetchOptionsGet())
.then((response) => {
if (response.ok) {
parseJSON(response)
.then(myData => {

dispatch(setDataInStore(myData));
dispatch(setDataInLocalStorage(myData));
})
} else {
// Handle error
}
})
}


The issue is with
setDataInLocalStorage
function. When I put
debuggers
, I see that I'm coming into
setDataInLocalStorage
and
myData
is populated by the API call.

What am I doing wrong there?

Answer Source

dispatch expects an action object to be returned. In this case setDataInLocalStorage doesn't return an action for dispatch to do anything with.

Since we only want to set localstorage, we can change the dispatch lines to this to:

dispatch(setDataInStore(myData));
setDataInLocalStorage(myData);

We treat setDataInLocalStorage() as a regular function being called.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download