Home > Blockchain >  Using React Redux Toolkit with Typescript - set state for reducer
Using React Redux Toolkit with Typescript - set state for reducer

Time:05-26

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:

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.

CodePudding user response:

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

 .addCase(setUser, (state, action) => ({ ...state, ...action.payload }))
  • Related