When I first open the app it gets the data from api but when I refresh the page it says Cannot read properties of undefined (reading 'memes'). When I console.log the store item It shows an empty object but I can see the api with Redux Devtools extension. I got stuck with this problem and can't figure it out for two days.
slice.js
import { createSlice, createAsyncThunk } from "@reduxjs/toolkit";
export const fetchJson = createAsyncThunk(
"json/fetchJson",
async () => {
const data = await fetch("https://api.imgflip.com/get_memes");
const json = await data.json();
return json;
}
);
export const loadJsonSlice = createSlice({
name: "loadJson",
initialState: {
isLoading: false,
hasError: false,
memes:{}
},
extraReducers: (builder) => {
builder
.addCase(fetchJson.pending, (state) => {
state.isLoading = true;
state.hasError = false;
})
.addCase(fetchJson.fulfilled, (state, action) => {
state.isLoading = false;
state.memes = action.payload;
})
.addCase(fetchJson.rejected, (state, action) => {
state.isLoading = false;
state.hasError = true;
state.memes = {};
});
}
});
export default loadJsonSlice.reducer;
export const selectAllJson = (state) => state.loadJsonReducer.memes;
export const isLoading = (state) => state.loadJsonReducer.isLoading;
display.js
import { useEffect, useState } from "react";
import { useSelector, useDispatch } from "react-redux";
import { selectAllJson, isLoading, fetchJson } from "./jsonSlice";
const DisplayJson = () => {
const allMemes = useSelector(selectAllJson);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchJson());
console.log(allMemes.data.memes[0].id); //Here is where the code gives error.
}, [dispatch]);
if (useSelector(isLoading)) {
return <h1 style={{ fontSize: "48px" }}>WAIT PUST</h1>;
}
return <div>{allMemes.data.memes[0].id}</div>; //Here is where the code gives error.
};
export default DisplayJson;
store.js
import { configureStore } from "@reduxjs/toolkit";
import loadJsonSlice from "./jsonSlice";
const store = configureStore({
reducer: {
loadJsonReducer: loadJsonSlice
}
});
export default store;