Property 'user' does not exist on type 'WritableDraft<{ name: string; }>'

Viewed 1905

i'm new with TypeScript. I'm trying to use TypeScript with Redux but i'm blocked with this error: Property 'user' does not exist on type 'WritableDraft<{ name: string; }>'. I was going step by step with tutorial on Youtube but it's not working on my project. Any ideas?

Here's my code:

import { createSlice } from '@reduxjs/toolkit';
import React from 'react';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    name: '',
  },
  reducers: {
    login: (state, action) => {
      state = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state: { user: { user: any } }) => state.user.user;

export default userSlice.reducer;
2 Answers

The data shape of the user state slice is { name: string }.

import { combineReducers, configureStore, createSlice } from '@reduxjs/toolkit';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    name: '',
  },
  reducers: {
    login: (state, action) => {
      state.name = action.payload;
    },
    logout: (state) => {
      state.name = '';
    },
  },
});

export const { login, logout } = userSlice.actions;

export const selectUser = (state: { user: { name: string } }) => state.user;

const store = configureStore({ reducer: combineReducers({ user: userSlice.reducer }) });
console.log(store.getState());
store.subscribe(() => {
  console.log('selectUser:', selectUser(store.getState()));
});

console.log(store.dispatch(login('John')));

Logs:

{ user: { name: '' } }
selectUser: { name: 'John' }
{ type: 'user/login', payload: 'John' }

If you've cross checked your code and its fine.

Change the version of redux-toolkit to a previous one, in my case, I used 1.8.0 and everything started working again.

Or delete node_modules and run npm install or yarn

Related