How to Update Multiple States with one Action and Thunks in Redux Toolkit | Answering a Commenter

In this video I answer a good question I got on my last video,
Chaining Asynchronous Dispatches in Redux Toolkit ( • Chaining Asynchronous ... ). It inspired me to make this entire video! We show how the extraReducers property of the Redux Toolkit createSlice function can be used to respond to other action types that were *NOT* created by that reducer itself. This means we can have one action trigger one, or ALL, of our reducers to trigger a state change across the application.
However, reducers are pure functions meaning no side effects can run within them. So if you have to fetch data and update state based on an outside action, that is a no no. We can handle that issue, though, by utilizing RTK's createAsyncThunk function. This has access to the ThunkAPI which is just the normal set of methods on our Redux store, such as getState and dispatch. We can then dispatch actions, still synchronously, within our thunk to other reducers as needed. Then the asynchronous code finishes and the "containment function" aka the thunk triggers its associated reducer to then update when fulfilled. BOOM ROASTED!
Link to the video where I build a quick Redux Toolkit Implementation if you need a crash course in it:
• How to Persist Redux S...
Don't forget to like this video and subscribe to our channel - we're publishing more videos and walkthroughs every week. Comment below and let us know what you'd like to see next!
Join the Covalence community: covalence.io
Shop Covalence merch: covalence.merchntly.com
#redux #reduxtoolkit #reducers #javascript #reactjs #react

Пікірлер: 13

  • @banjobsiramanont4566
    @banjobsiramanont45664 ай бұрын

    Thnk you so much for making this video. Problem solved!!!

  • @lethe_yoon
    @lethe_yoon10 ай бұрын

    This is great! I was wondering about updating multiple different slice states, but didn't know how to implement it with RTK. Now, I got the niche, thank you you're my best tutor!

  • @covalence-io

    @covalence-io

    10 ай бұрын

    Let's gooooo! These kinda' comments make my day

  • @mikeedwards2378
    @mikeedwards2378 Жыл бұрын

    Thanks so much for this! Weirdly enough, today I had exactly that first case you addressed with the actions coming from another slice (but not needing to kick off a fetch or anything.) If I'd searched for an answer to this just a few hours earlier, I'd have missed this video and would've spent hours chasing my tail looking for the proper RTK way to do this-which is this! And it works perfectly in Typescript! And with none of the painful type stuff you sometimes get in async thunks!

  • @covalence-io

    @covalence-io

    Жыл бұрын

    Happy to help!

  • @ahmadpak
    @ahmadpak7 ай бұрын

    Thank you. Helped me clear my concepts.

  • @user-sf3hm4db7y
    @user-sf3hm4db7y8 ай бұрын

    Thanks, Clear and perfect explanation

  • @prashantmestry8199
    @prashantmestry81996 ай бұрын

    Informative video. Thank you

  • @xmatthewday
    @xmatthewday6 ай бұрын

    Excellent explanation, thank you. Do you have this in a GH repo, by chance?

  • @user-jm7yy2kv4p
    @user-jm7yy2kv4p Жыл бұрын

    That's a great explanation, thank you for this. If there are multiple APIs to call one after other , is this the best way to handle in RTK? Say, I have to call one API then based on the data fetched, I have store it in redux store and with that data I have to call another API (Asynchronous chaining). So, for this requirement , is this the right way - what you showed in this video?

  • @covalence-io

    @covalence-io

    Жыл бұрын

    The RTK docs and maintainers say just to use RTK Query for this stuff and I'd recommend the same if you're on a deadline. It can handle multiple calls, cache results, and handle loading states. If you want to learn how to write it yourself as a student of code then you can chain them by using dispatch returning an action that returns a promise. You can chain .then off a returned dispatch(myAsyncThunk())

  • @nikhilgupta2569
    @nikhilgupta2569 Жыл бұрын

    Great video @covalence but my use case is I have a single asyncThunk(getUserDataById in your example). I do not want other side effects(dispatch calls inside to other reducers), I need to return data from asyncThunk and make multiple slices listen for that data. Slice 1 import { fetchAdmin } from '../thunks/fetchAdmin'; const adminSlice = createSlice({ name: 'admin', initialState: {}, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchAdmin.fulfilled, (state, {payload}) => { state.data = payload; }) } }); Slice 2 import { fetchAdmin } from '../thunks/fetchAdmin'; const userSlice = createSlice({ name: 'admin', initialState: {}, reducers: {}, extraReducers: (builder) => { builder.addCase(fetchAdmin.fulfilled, (state, {payload}) => { state.data = payload; }) } }); With this approach I do see my userSlice's extraReducer getting called with the correct payload however user state is not changing. I understand when we call asyncThunk it is associated with a specific sliceKey/action. Is this the reason why state of other slice reducer wouldn't change?

  • @covalence-io

    @covalence-io

    Жыл бұрын

    Try to see if changing the "name" property on your slices since in the code you copied here both have them assigned as "admin" and that may make a difference. Otherwise a non-hacky and more redux-y approach would be to make a custom thunk that can dispatch to both slices. The asyncThunks in RTK have access to all your traditional store methods in redux, too. E.g. our good friend dispatch() // In your thunks file export const fetchAdminAndUser = createAsyncThunk( 'adminAndUser/fetch', async (_, { dispatch }) => { const admin = await api.fetchAdmin(); const user = await api.fetchUser(); // Dispatch separate actions for admin and user dispatch(fetchAdminFulfilled(admin)); dispatch(fetchUserFulfilled(user)); } );