0

I just started using redux, and I'm trying to fetch some data from Firebase and put it in my store. I did some research into the matter and it looked like to me that this:

export const addData = (database) => {
  return dispatch => database.ref.once('value').then((snapshot) => {
    dispatch({
      type: 'STORE_DATA',
      payload: snapshot.val()
    });
  }, (err) => {
    dispatch(
    {type: 'STORE_FAILED'})
  })
}

should work, however I am getting an error "Error: Actions must be plain objects. Use custom middleware for async actions" when I call

store.dispatch(addData(firebase.database()))

I'm not sure what I'm doing wrong.

1 Answer 1

3

You need to use a custom middleware like redux thunk or sagas in order to create an action as a function instead of a plain object.

npm i redux-thunk

Then import this into the file where your store is located.

import thunk from 'redux-thunk'

And add it as an argument to your applyMiddleware function and applyMiddleware as an argument to your createStore function.

const store = createStore(rootReducer, 
applyMiddleware(
    thunk
  )
);

This should give you the ability to run your async function inside your action.

Sign up to request clarification or add additional context in comments.

1 Comment

Also, don't forget to restart your dev server after you install your dependency as those changes may not take effect until you do so

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.