Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

(TS – Redux) How to initialize state property as null: Type 'UserData' is not assignable to type 'null'

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
      }
    }
  }
})

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading