Where to dispatch multiple actions in redux?

前端 未结 7 1665
终归单人心
终归单人心 2021-01-31 08:10

I am using redux with connect and redux-thunk middleware and containers.

Currently when an user perform an action, example one click on a butto

7条回答
  •  Happy的楠姐
    2021-01-31 08:44

    For guys in 2020... The actions are Supposed to be made in the action Creater. For those who would like to dispatch an action and fetch/post some data from the API can use this Idea.

    lets assume we have an actions.js file and we want to dispatch a loading action before fetch data.

    function requestPosts() {
        return {
          type: "loading"
        }
      }
    

    This is the fetching action function

    function fetchPosts() {
     return dispatch => {
        // dispatch the loading
        dispatch(requestPosts());
        // fetch data from api
      return fetch("https://www.yoururl.com/api")
       .then(response => response.json())
       .then(json => dispatch({
           type: "fetching successful",
           payload: json
        }));
      }
    }
    

提交回复
热议问题