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

前端 未结 3 1721
遇见更好的自我
遇见更好的自我 2021-01-22 20:04

Below is the code for my action creator:

export function fetchPosts()
  {
    const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
    return
      {
               


        
3条回答
  •  悲哀的现实
    2021-01-22 20:57

    As per redux documentation:

    Actions are plain JavaScript objects. Actions must have a type property that indicates the type of action being performed. Types should typically be defined as string constants. Once your app is large enough, you may want to move them into a separate module.

    And Action Creators

    Action creators are functions that create actions

    In Redux action creators simply return an action:

    function addTodo(text) {
      return {
        type: ADD_TODO,
        text
      }
    }
    

    So when you call the action creator from your component through dispatch your action creator just needs to simply return a plain javascript object.

    So a normal action creator will be

    export function fetchPosts()
      {
    
        return
          {
            type: FETCH_POSTS;
            payload: "somevalue"
    
          };
      }
    

    Now if you want to call APIs within your action creators you need to make use of middlewares like redux-thunk or redux-saga while creating a store

    like

    import thunk from 'redux-thunk';
    const store  = createStore(reducers, applyMiddleware(thunk));
    

    You you configure your store with middleware you can modify your actions to

    export function fetchPosts() {
        return (dispatch) =>  {   
            axios.get(`${ROOT_URL}/posts${API_KEY}`)
                   .then((response)=> {
                         dispatch( {
                               type: FETCH_POSTS,
                               payload: request
    
                         })
                    })  
            } 
    
         }
    

    As per the redux-thunk documentation

    Why Do you need redux-thunk?

    Redux Thunk middleware allows you to write action creators that return a function instead of an action. The thunk can be used to delay the dispatch of an action, or to dispatch only if a certain condition is met. The inner function receives the store methods dispatch and getState as parameters.

提交回复
热议问题