Mahesh Kumaran
Mahesh Kumaran

Reputation: 907

How to make async calls in prepare method of createSlice of redux-toolkit?

I have the following createSlice method. I looked into the documentation of createSlice where they have given an option to use the prepare method to customize the action creation.

I'm trying to make an API call, However the reducer is triggered before the API response. Hence my action.payload remains undefined.

Can prepare be used to make async calls ?

PS: I did not want to maintain my customized action creators in a separate function/file. The purpose of using createSlice is to improve code maintainability.

export const authReducers = createSlice({
    name: "auth",
    initialState: { ...initialState },
    reducers: {
        loginToConsole: {
            reducer: (state, action) => {
                console.log("Reducer Called", action);
                state.isLoggedIn = !state.isLoggedIn;
            },
            prepare: async (credentials) => {
                let response = await axios.post(
                    `${apiEndPoint}/api/auth/login`,
                    credentials
                );

                console.log(response);
                return { payload: { ...response.data } };
            },
        },
    },
});

Upvotes: 1

Views: 1298

Answers (1)

phry
phry

Reputation: 44186

No, it cannot. prepare is called synchronously.

You should use thunks for that - see This Chapter of the official Redux tutorial

That said, nothing prevents you from writing your thunks just in the same file. Many people do that.

Upvotes: 2

Related Questions