Skip to content Skip to sidebar Skip to footer

Redux-thunk: Api Response Keeps Pending

I am trying to develop an application, that is showing photos from Unsplash given a keyword. I managed to fetch specific photos using unsplash.js. In my actions, I have several act

Solution 1:

In the below code you assign a promise to response, then console.log that promise, and then return the action with payload set to that promise.

const response = unsplash.search
  .photos(term, 1, 20)
  .then(toJson)
  .then(json => json)
  .then(json => json)

console.log(response.then(results => results));
return {
  type: RECEIVE_PHOTOS,
  payload: response
};

dispatch(receivePhotos(term)); then dispatches that action, still with the payload as a promise. maybe this would work if you had middleware that could handle it.

This use of dispatch suggests that you are using redux-thunk though. In that case, you should do the same with receivePhotos, include the fetchPhotos call, and retire the unsplash action.

const unsplashClient = newUnsplash({
  applicationId:
    "id",
  secret: "secret",
  callbackUrl: "callback"
});

exportconstreceivePhotos = term => dispatch => {
  dispatch(fetchPhotos());
  return unsplashClient.search
    .photos(term, 1, 20)
    .then(toJson)
    .then(json =>dispatch({
      type: RECEIVE_PHOTOS,
      payload: json
    });
}

In the end I would suggest a bit of refactoring of the actions and the (related reducers) such as:

const unsplashClient = newUnsplash({
  applicationId:
    "id",
  secret: "secret",
  callbackUrl: "callback"
});

exportconstfetchingPhotos = payload => ({
  type: FETCHING_PHOTOS, payload
});

exportconstsetPhotos = payload => ({
  type: SET_PHOTOS, payload
});

exportconstfetchPhotos = term => dispatch => {
  dispatch(fetchingPhotos(true));
  return unsplashClient.search
    .photos(term, 1, 20)
    .then(toJson)
    .then(json => {
      dispatch(setPhotos(json));
      dispatch(fetchingPhotos(false));
    });
}

Post a Comment for "Redux-thunk: Api Response Keeps Pending"