Search code examples
javascriptreactjsredux

Data is not being stored in redux store


store imageI am going to store the data into the react-redux-store but it is not getting stored. I don't understand what I am missing...I have given my code below.

i am trying to store the data from the api but it is not working...

INDEX.JS

import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
import { Provider } from "react-redux";
import { store } from "./features/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);

STORE.JS

import { configureStore } from "@reduxjs/toolkit";
import moviesReducer from "./movies/movieSlice";

export const store = configureStore({
  reducer: moviesReducer,
});

MOVIE SLICE.JS

import { createSlice } from "@reduxjs/toolkit";

const initialstate = {
  movies: [],
};

const movieSlice = createSlice({
  name: "movies",
  initialstate,
  reducers: {
    addMovies: (state, { payload }) => {
      state.movies = payload;
    },
  },
});

export const { addMovies } = movieSlice.actions;
// export const getAllMovies = (state) => state.movies.movies;
export default movieSlice.reducer;

COMPONENT

import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import MovieAPI from "../config/MovieAPI";
import { addMovies } from "../features/movies/movieSlice";

const Home = () => {
  const dispatch = useDispatch();

  const fetchMovies = async () => {
    const response = await MovieAPI.get(`?apiKey=1234&s=harry&type=movie`);
    console.log(response.data);
    dispatch(addMovies(response.data));
  };

  useEffect(() => {
    fetchMovies();
  }, []);

Solution

  • For the very first: createSlice expecting to recieve object with property named initialState instead initialstate, notice camelCase naming.

    The next one: acording to location and slice name "movies" I may suspect you should define it as: const initialState = [];, due to it is "movies slice" initial state definition itself, otherwise you will have state with something like state = {movies: {movies: []}}.

    Also, you may wish to rewrite addMovies reducer in something like:

        addMovies: (moview_slice_state, { payload }) => {
          console.log("add movies", payload);
          moview_slice_state.push(...payload);
        }
    

    where moview_slice_state - state of movies slice of whole state, e.g. state.movies.

    By the way, due to @reduxjs/toolkit use immer under the hood you may "modify" state OR return new state, as Andrej Kirejeŭ propose. But NOT the both of them.

    P.S. For the future, feel free to create minimal demo for your question or answer, some thing like live demo based on your code