0

I am new to redux , redux toolkit and I got an error message that I really struggle to deal with but i need some help. Any help will be appreciated. Thanks in advance

My error :

ERROR TypeError: undefined is not an object (evaluating 'state.favorites.favorites')

my code :

reducer.ts

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { IFavorite, MEATPROPS, IFavoriteState } from "../../../types/meat";
const initialState = {
  favorites: [],
};

const FavoriteData = createSlice({
  name: "favoriteData",
  initialState,
  reducers: {
    addNewFavoriteCharacter: (
      state: IFavorite,
      action: PayloadAction<MEATPROPS>
    ) => {
      state.favorites = [...state.favorites, action.payload];
    },
    removeFavoriteCharacter: (
      state: IFavorite,
      action: PayloadAction<number>
    ) => {
      state.favorites = state.favorites.filter(
        (item) => item.id !== action.payload
      );
    },
  },
});

export const { addNewFavoriteCharacter, removeFavoriteCharacter } =
  FavoriteData.actions;

export const favoriteStateData = (state: IFavoriteState) =>
  state.favorites.favorites;
  

export default FavoriteData.reducer;

app.tsx

import React, { useCallback } from "react";
import { SafeAreaProvider } from "react-native-safe-area-context";
import { AppNavigation } from "./src/appNavigation";
import { useFonts, Poppins_500Medium } from "@expo-google-fonts/poppins";
import * as SplashScreen from "expo-splash-screen";
import { Provider } from "react-redux";
import {PersistGate} from 'redux-persist/es/integration/react';
import { persistor, store } from "./src/store";
export default function App() {
  const [fontsLoaded] = useFonts({
    Sangharia: require("./src/fonts/Sangharia.ttf"),
    Poppins_500Medium: Poppins_500Medium,
  });
  const onLayoutRootView = useCallback(async () => {
    if (fontsLoaded) {
      await SplashScreen.hideAsync();
    }
  }, [fontsLoaded]);
  if (!fontsLoaded) {
    return null;
  }
  return (
    <Provider store={store}>
      <PersistGate loading={null} persistor={persistor}></PersistGate>

      <SafeAreaProvider onLayout={onLayoutRootView}>
        <AppNavigation />
      </SafeAreaProvider>
    </Provider>
  );
}

types.ts

export interface MEATPROPS {
  id: number;
  meatType: "Beef" | "Pork" | "Sheep" | "Chicken";
  image?: any;
  name: string;
  simplifiedDescription?: string;
  fullDescription?: string;
  countriesNaming?: countries;
  bestTo: string[];
  popularity?: "baixa" | "tradicional" | "alta";
  nutriFact?: Nutrition;
}
export interface IFavorite{
  favorites: MEATPROPS[]
}
export interface IFavoriteState{
  favorites:{
    favorites: MEATPROPS[]
  }

}

store


import { configureStore } from "@reduxjs/toolkit";
import {
  persistStore,
  persistReducer,
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from "redux-persist";
import AsyncStorage from "@react-native-async-storage/async-storage";

import favoriteData from "./modules/Favorites/reducer";
const persistConfig = {
  key: "root",
  storage: AsyncStorage,
};
const persistedReducer = persistReducer(persistConfig, favoriteData);
const store = configureStore({
  reducer: {
    favoriteData: persistedReducer,
  },
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
});
const persistor = persistStore(store);
export { store, persistor };



I'm trying to persist data on local storage

3
  • Let's see your store setup. Commented Jan 22, 2023 at 22:18
  • I just added above Commented Jan 22, 2023 at 22:23
  • see here full code with redux may be this will help you codesandbox.io/s/loving-cloud-jhlqqr?file=/src/App.js:0-2307 Commented Jan 23, 2023 at 9:29

1 Answer 1

1

Your slice name is "favoriteData". When you call favorites from the state you should use state.favoriteData.favorites not state.favorites.favorites

Fix this code:

export const favoriteStateData = (state: IFavoriteState) =>
  state.favoriteData.favorites  // use this here

I hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.