Ajay Kumar Ajay Kumar - 8 months ago 35
Javascript Question

how to handle middleware by request action and trigger success action in react+redux?

I am learning ReactJS by a movie finder app using reactJS+redux. I am putting my github repo here:

https://github.com/ajay28kumar/redux-omdb-movieFind.git


I am creating one action called getMovieSearch that will return the requested data in component as well as make an api call (api call file is in
/api/fetchApi
). After fetching data into api file I am passing that dta to my successAction named getMovieList and after that I am returning the same into my reducer movieGetReducer. All of these steps are working fine but my store is not getting updated.

I got one alternate solution that getMovieSearch will make following call:

export var getMovieSearch = (payload) => {
const request= axios.get("http://www.omdbapi.com/?t="+ payload+ "&page=1");
console.log("data from api :", request)
return {
type: 'GET_MOVIE_LIST',
payload: request
};
};


It is going to my middleware and working fine but I want to seperate actions for request / successResponse / errorResponse for my learning app.

If someone can correct the same then it will great.

Thanks.

Answer Source

You can use redux-thunk. A common pattern for async actions is that you create 3 actions: request, receive (success) and failed.

Example:

export var getMovieSearch = (payload) => (dispatch) => {
  dispatch(requestMovieList(payload));
  axios.get("http://www.omdbapi.com/?t=" + payload + "&page=1")
    .then(res => dispatch(receiveMovieList(res.data)))
    .catch(err => dispatch(getMovieListFailed(err)))
};