how to chain asynchronous actions with Redux thunk

Asked

Viewed 9 times

0

I am trying to make two actions, being addToFavorite and removeToFavorite, be updated immediately upon hearing the click of a button, updating the "Favoritar" button to "Remove from favorites" or the other way around. But this is not happening immediately, and it takes two clicks. Follow my actions:

export const addToFavorite =  (track) => async () => {
  const {action: id} = track

  const { data } = await api.put(`/me/tracks?ids=${id}`);
 
  return dispatch => { 
      dispatch({
      type: 'PUT_FAVORITE',
      payload:  data
    }).then(
      response => {
        dispatch({ type: 'PUT_FAVORITE_SUCCESS', data,  response })
      },
      error => {
        dispatch({ type: 'GET_USER_FAILURE', data,  error })
        throw error
      }
    )
  }  
}

export const removeToFavorite =  (track) => async () => {
  const {action: id} = track

  const { data } = await api.delete(`/me/tracks?ids=${id}`);
 
  return dispatch => { 
      dispatch({
      type: 'PUT_FAVORITE',
      payload:  data
    }).then(
      response => {
        dispatch({ type: 'DELETE_FAVORITE_SUCCESS', payload:  data,  response })
      },
      error => {
        dispatch({ type: 'DELETE_FAVORITE_FAILURE', payload:  data,  error })
        throw error
      }
    )
  }  
}

And the function that calls one of the actions:

 function handleOnClickFavorite(itemId){
    if(listFavorites && listFavorites.length > 0 && listFavorites.find((favoriteSong) => favoriteSong.id === itemId)){
      dispatch(removeToFavorite({type: 'DELETE_FAVORITE', action: itemId}))
    }else{ 
      dispatch(addFavorite({type: 'PUT_FAVORITE', action: itemId}))
    }
    dispatch(getFavorite());
  }

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.