score:5

from user acemark on the reactjs subreddit:

fwiw, nothing about making async calls with redux changes with redux toolkit at the moment.

you'd still use an async middleware (typically redux-thunk), fetch data, and dispatch actions with the results.

the next version of redux toolkit will include a helper method called createasyncthunk that does some of the action dispatching for you, but it's still the same standard process.

so, in general, your slice file would have something like:

const usersslice = createslice({
    name: "users",
    initialstate: {
        loading: 'idle',
        users: []
    },
    reducers: {
        usersloading(state, action) {
            // use a "state machine" approach for loading state instead of booleans
            if(state.loading === 'idle') {
                state.loading = 'pending'
            }
        },
        usersreceived(state, action) {
            if(state.loading === 'pending') {
                state.loading = 'idle'
                state.users = action.payload
            }
        }
    }
})

const {usersloading, usersreceived} = usersslice.actions;

const fetchusers = () => async dispatch => {
    dispatch(usersloading());
    const response = await usersapi.fetchall()
    dispatch(usersreceived(response.data));

}

and then you'd do dispatch(fetchusers()) in your component somewhere.

hopefully that points you in the right direction!


Related Query

More Query from same tag