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

Using React Redux Toolkit with Typescript – set state for reducer

I’m trying to use React Redux Toolkit with TypeScript and I’m facing this issue with the creation of the reducer for the User model.

This is my userReducer.ts file:

import { createReducer } from "@reduxjs/toolkit";
import { UserModel } from "../../models/UserModel";
import {setUser, getUser, removeUser} from "../actions/userActions";

const initialState: UserModel = {
  email: "",
  id: "",
}

export const userReducer = createReducer(initialState, (builder) =>
  builder
    .addCase(getUser, (state) => state)
    .addCase(removeUser, () => initialState)
    .addCase(setUser, (state, action) => { ...state, ...action.payload })
);

I’m having issues with the last addCase for setting the user, intellisense says:

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

A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556)
Cannot find name 'state'.ts(2304)

I don’t understand how to fix it and more in general how to set the state properly using Redux with Typescript.

>Solution :

I suppose you want to return state updated with action.payload?:

 .addCase(setUser, (state, action) => ({ ...state, ...action.payload }))
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