I been at this for hours.. I'm fairly new to redux and redux toolkit
I currently have a signup form and when I try to sign up, it updates my backend which is using mongoDB, however it does not update my state in redux which I can't figure out.
appApi.js
import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';
export const appApi = createApi({
reducerPath: 'appApi',
baseQuery: fetchBaseQuery({ baseUrl: 'http://localhost:8001' }),
endpoints: builder => ({
signup: builder.mutation({
query: user => ({
url: '/users/signup',
method: 'POST',
body: user,
}),
}),
login: builder.mutation({
query: user => ({
url: '/users/login',
method: 'post',
body: user,
}),
}),
}),
});
export const { useSignupMutation, useLoginMutation } = appApi;
export default appApi;
userSlice.js
import { createSlice } from '@reduxjs/toolkit';
import appApi from '../services/appApi';
const initialState = null;
export const userSlice = createSlice({
name: 'users',
initialState,
reducers: {},
extraReducers: builder => {
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(_, { payload }) => {
console.log(_); // null why?
console.log(payload); //null why?
return payload;
}
);
builder.addMatcher(
appApi.endpoints.login.matchFulfilled,
(_, { payload }) => payload
);
},
});
export default userSlice.reducer;
EDIT SOLVED
I figured it out, my frontend was correct, it was my backend that was wrong.
This was inside my users model file.
I forgot to add () at end of user.toObject;
what I had before
UserSchema.methods.toJSON = function () {
const user = this;
const userObject = user.toObject; <----- this was the problem
delete userObject.password;
return userObject;
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(_, { payload }) => {
console.log(_); // null why?
console.log(payload); //null why?
return payload;
}
In this code, _
is state
- above that you declared initialState
to be null
- so that explains that null
.
As for the payload, that is interesting but honestly I also don't quite believe that that's null
unless the server would explicitly return that. Maybe take a look at the full action to see what's going on.
builder.addMatcher(
appApi.endpoints.signup.matchFulfilled,
(state, action) => {
console.log({state, action});
return action.payload;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.