score:13

Accepted answer

this is covered in the redux faq entry on sharing state between reducers.

pasting the key points:

  • if a reducer needs to know data from another slice of state, the state tree shape may need to be reorganized so that a single reducer is handling more of the data.
  • you may need to write some custom functions for handling some of these actions. this may require replacing combinereducers with your own top-level reducer function. you can also use a utility such as reduce-reducers to run combinereducers to handle most actions, but also run a more specialized reducer for specific actions that cross state slices.
  • async action creators such as redux-thunk have access to the entire state through getstate(). an action creator can retrieve additional data from the state and put it in an action, so that each reducer has enough information to update its own state slice.

score:0

i think you could use thunkapi and extrareducers like below, assuming that you have an auth slice which has the current user object:

import { createslice, createasyncthunk } from "@reduxjs/toolkit";
import ordersservice from "./ordersservice";

const initialstate = {
    orders: [],
    iserror: false,
    issuccess: false,
    isloading: false,
    message: "",
};

//get orders
export const getorders = createasyncthunk(
    "orders/getorders",
    async (__, thunkapi) => {
        try {
            const userid = thunkapi.getstate().auth.user.id
            return await ordersservice.getorders(userid);
        } catch (error) {
            const message =
                (error.response &&
                    error.response.data &&
                    error.response.data.message) ||
                error.message ||
                error.tostring();
            return thunkapi.rejectwithvalue(message);
        }
    }
);

export const ordersslice = createslice({
    name: "orders",
    initialstate,
    reducers: {
        reset: (state) => {
            state.iserror = false;
            state.issuccess = false;
            state.isloading = false;
            state.message = "";
        },
    },
    extrareducers: (builder) => {
        builder
            .addcase(getorders.pending, (state) => {
                state.isloading = true;
            })
            .addcase(getorders.fulfilled, (state, action) => {
                state.isloading = false;
                state.issuccess = true;
                state.orders = action.payload;
            })
            .addcase(getorders.rejected, (state, action) => {
                state.isloading = false;
                state.iserror = true;
                state.message = action.payload;
                state.orders = [];
            });
    },
});

export const { reset, setorder } = ordersslice.actions;
export default ordersslice.reducer;

Related Query

More Query from same tag