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.
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.
CodePudding user response:
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: '',
};