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

前端 未结 3 1716
遇见更好的自我
遇见更好的自我 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 21:07

    GibboK's answer has already pointed out the syntax error.

    However, I don't think you understand using actions properly. You run:

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

    This is creating a promise. You are currently returning this in an action. Reducers are meant to be deterministic & side effect free, hence why actions should be plain JS objects. You should not be submitting a promise.

    Instead, you should be using some relevant middleware, e.g. redux-thunk, redux-saga or something else. You should send an action when the actual promise has resolved.

    As a simple contrived example, using redux-thunk:

    export const fetchPosts = () => (dispatch) => {
        // Send action to notify request started. Reducers often want to
        // update the state to record that a request is pending, e.g. for
        // UI purposes.
        dispatch({type: FETCH_POSTS_START});
    
        // Start request
        request = axios.get(`${ROOT_URL}/posts${API_KEY}`)
           .then(res => { 
              // Successfully received posts, submit response data
              dispatch({type: FETCH_POSTS_COMPLETE, payload: res.data})
            })
           .catch(err => { 
              // API call failed, submit error
              dispatch({type: FETCH_POSTS_ERROR, payload: err})
            });
    };
    

    Note this code is just an example and not necessarily suitable for use in a production system.

提交回复
热议问题