1

I want to make a react redux using typescript but got an error. I use cra redux typescript template for the installation. I delete the counter reducer, and a new reducer using slice.

I want to specify my error is in the initialState at userSlice.ts with the following error.

enter image description here

enter image description here

Here is type.ts

export interface ExplicitContent {
  filter_enabled: boolean;
  filter_locked: boolean;
}

export interface ExternalUrls {
  spotify: string;
}

export interface Followers {
  href?: any;
  total: number;
}

export default interface UserType {
  country: string;
  display_name: string;
  explicit_content: ExplicitContent;
  external_urls: ExternalUrls;
  followers: Followers;
  href: string;
  id: string;
  images: any[];
  product: string;
  type: string;
  uri: string;
}

Here is userSlice.ts

import { createSlice } from '@reduxjs/toolkit';
import UserType from '../../types/user';

interface UserState {
  user: UserType;
  token: string;
}

const initialState: UserState= {
  user: null,
  token: '',
};

export const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setToken(state, action) {
      return {
        ...state,
        token: action.payload,
      };
    },
    setUser(state, action) {
      return {
        ...state,
        user: action.payload,
      };
    },
  },
});

I don't know if my reducer or the initialstate have a wrong syntax or something. I use json2ts.com to change json response from the api call, so I think there is no problem about it. But I'm not sure about my code in the reducer. Please give me solution for this, thank you in advance.

#note: I'm not changing anything about hooks.ts and store.ts from the template except the configurestore to import my reducer.

Hera Zeus
  • 123
  • 1
  • 10

1 Answers1

3

The initialState variable needs to be UserState. Additionally, user property in UserState currently cannot be null, hence you will have to add a null union type to it in order for initialState to be valid.

interface UserState {
  user: UserType | null;
  token: string;
}
const initialState: UserType = {
  user: null,
  token: '',
};
Ovidijus Parsiunas
  • 2,512
  • 2
  • 8
  • 18
  • Thank you for the solution, it works fine now. But I want to ask something, I tried to change the initialState to `const initialState: UserState | {} = {code}` but not work. Is this wrong use of `null` type? – Hera Zeus Apr 16 '22 at 14:22
  • I am not sure what ```code``` is. But given that it is not part of ```UserState``` type, I would say that it is incorrect. – Ovidijus Parsiunas Apr 17 '22 at 09:13
  • If my answer helped with your original question, would you mind accepting it :) – Ovidijus Parsiunas Apr 17 '22 at 09:13
  • Oops sorry forgot it. And yes, I can't declare initial state like that, just see the documentation – Hera Zeus Apr 17 '22 at 09:43