I'm having this error: Type 'UserData' is not assignable to type 'null'.
I defined the user state property as user: UserData | null;... So i don't understand why it doesn't let me to initialize the property as null and then assign it a UserData like value: Error Console
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";
interface AppState {
user: UserData | null;
}
const appSlice = createSlice({
name: 'app',
initialState: { user: null },
reducers: {
loadUserIntoApp: {
reducer(state, action: PayloadAction<UserData>) {
state.user = action.payload; // This is the line with an error
}
}
}
})
CodePudding user response:
You should infer the AppState interface to the initialState
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { UserData } from "../../types/user";
interface AppState {
user: UserData | null;
}
const appSlice = createSlice({
name: 'app',
initialState: AppState = { user: null },
reducers: {
loadUserIntoApp: {
(state, action: PayloadAction<UserData>) => { //you should add the reducer like this
state.user = action.payload;
}
}
}
})
go to decumetation for more info