Home > Software engineering >  Can I return value from action creator using redux-thunk?
Can I return value from action creator using redux-thunk?

Time:02-14

I've seen a lot of examples of async action creators, but they all do some sort of fetching and pushing data to redux store and return nothing. I need another logic that looks something like:

const createUserAction = (user) => {
  firestore().collection('users').add(user)
  .then(result => {
     dispatch({type: 'SET_USER', payload: {...user, id: result.id}})
  })
}

I need to return result.id from createUserAction to navigate to page that displays user by his id. In my imagine it should work like

createUserAction({name: John}).then(id => navigation.navigate('UserDetailPage', {userId: id}))

I don't know how to implement that and I'll be glad if somebody can help

CodePudding user response:

Returning values from action creators is a No-Go. The solution for this scenario that I've used and think is better is to do the redirect in the async action itself:

// afterCreation = callback function with one argument, the created user
const createUserAction = async (user, afterCreation) => {
  const createdUser = await firestore().collection('users').add(user);
  dispatch({type: 'SET_USER', payload: {...user, id: createdUser.id}});
  afterCreation(createdUser);
};

createUserAction(
  {name: John},
  // Pass callback to action creator
  (user) => navigation.navigate('UserDetailPage', {userId: user.id})
);
  • Related