I am using rest countries api to fetch all countries, and i am suppose to add any country to favourite page saving it in localstorage but i am having error adding and removing an item in the array in localstorage in the slice i created
here is my code
import { createSlice } from "@reduxjs/toolkit";
import type { PayloadAction } from "@reduxjs/toolkit";
type Country = {
flags: {
svg: string;
};
name: {
common: string;
};
region: string;
capital: string[];
population: number;
};
interface initials {
post: Country[];
postNumber: number;
}
const temp = localStorage.getItem("postItem");
const tempNumber = localStorage.getItem("postNumber");
const initialState: initials = {
post: temp ? JSON.parse(temp) : [],
postNumber: tempNumber ? JSON.parse(tempNumber) : 0,
};
export const postSlice = createSlice({
name: "Post",
initialState,
reducers: {
addToFavourite: (state, action: PayloadAction<Country>) => {
state.post.push(action.payload), (state.postNumber += 1);
localStorage.setItem("postItem", JSON.stringify(state.post));
localStorage.setItem("postNumber", JSON.stringify(state.postNumber));
},
removeFavourite: (state, action: PayloadAction<string>) => {
const postId = action.payload;
const removeItem = (state.post = state.post.filter(
(post) => post.name.common !== postId,
));
state.post = removeItem;
localStorage.setItem("postItem", JSON.stringify(state.post));
},
},
});
export const { addToFavourite, removeFavourite } = postSlice.actions;
export default postSlice.reducer;