Ahmed Abumostafa
Ahmed Abumostafa

Reputation: 218

react redux nested dispatch not called

i'm using redux with react native and i need to re-use my actions

const fetchPosts = () => {

  return (dispatch) => {

    Api.get('/posts')
       .then(response => dispatch({type: FETCH_POSTS_SUCCESS, payload: response}))
       .catch(err => dispatch({type: FETCH_POSTS_FAIL, payload: err}))
  }
}

i want to always fetch posts after login

const login = ({username, password}) => {

  return (dispatch) => {

    Api.post('/auth', {username, password})
       .then(response => dispatch({type: LOGIN_SUCCESS, payload: response})
       .then(() => fetchPosts())
       .catch(err => dispatch({type: LOGIN_FAIL, payload: err}))
  }
}

the problem is fetch posts dispatch never happen because.

any suggestions?

Upvotes: 0

Views: 2304

Answers (2)

Spark.Bao
Spark.Bao

Reputation: 5743

You should dispatch(fetchPosts()), and you can directly call it after dispatch({type: LOGIN_SUCCESS, payload: response} in the same then callback, or keep it in the second then callback, they are both ok:

const login = ({username, password}) => {

  return (dispatch) => {

    Api.post('/auth', {username, password})
      .then(response => {
        dispatch({type: LOGIN_SUCCESS, payload: response}
        dispatch(fetchPosts())
      })
      .catch(err => dispatch({type: LOGIN_FAIL, payload: err}))
  }
}

Upvotes: 1

Mμ.
Mμ.

Reputation: 8542

The main reason the code is not working is because fetchPosts did not return a promise. Try the following code:

const fetchPosts = (dispatch) => {
    return Api.get('/posts')
       .then(response => dispatch({type: FETCH_POSTS_SUCCESS, payload: response}))
       .catch(err => dispatch({type: FETCH_POSTS_FAIL, payload: err}))
}

const login = ({username, password}) => {
  return (dispatch) => {
    Api.post('/auth', {username, password})
       .then(response => dispatch({type: LOGIN_SUCCESS, payload: response})
       .then(() => fetchPosts(dispatch))
       .catch(err => dispatch({type: LOGIN_FAIL, payload: err}))
  }
}

Upvotes: 0

Related Questions