Call an action from another action using Redux Toolkit

There are multiple ways to call an action from another action using Redux Toolkit. Here, we’ll discuss two different methods with a small example.

Way to call an action from another action

  1. Using dispatch function
  2. Using createAction function

1. Using dispatch function

In Redux Toolkit, you can use the dispatch function to call an action from another action. Here is an example of how to do this:

In the above example, we have two actions: fetchUser and updateUser. The updateUser action takes a userId parameter and a dispatch parameter, which is provided by Redux Toolkit. Inside the updateUser action, we make an API call to update the user data and then call the fetchUser action using dispatch to fetch the updated user data.

To handle these actions in the user slice, we use the extraReducers field in createSlice to listen for the fulfilled action of each of these actions and update the state accordingly.

Overall, Redux Toolkit makes it easy to call actions from other actions using the dispatch function, allowing you to easily manage complex state changes in your Redux store.

2. Using createAction function

In the above example, the updateAndFetchUser action calls the updateUser and fetchUser actions using the dispatch function passed as an argument. This way, you can call one action from another and orchestrate more complex behavior in your Redux store.

I hope you find this article helpful.
Thank you for reading. Happy Coding..!! 🙂

If you found value in this article,
you can support us by buying me a coffee! ☕

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *