skip to Main Content

I’m trying to use Redux to set a boolean in the state to show/hide an element.

Whenever I dispatch a boolean the following error shows:
A non-serializable value was detected in the state, which is weird as a boolean is perfectly serializable?

Todo.js

import { useSelector, useDispatch } from "react-redux";

export default function Planner() {
  const dispatch = useDispatch();

  function createHandleClickOpen() {
    dispatch(createDialogOpen(true));
  }

createHandleClickOpen is bound on a button’s onClick() method.

Plannerstore.js

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

export const plannerSlice = createSlice({
  name: "planner",
  initialState: {
    createDialogOpen: false,
  },
  reducers: {
    createDialogOpen: (state) => (value) => {
      state.createDialogOpen = value;
    },
  },
});

// Action creators are generated for each case reducer function
export const { createDialogOpen } = plannerSlice.actions;

export default plannerSlice.reducer;

Store.js

import { configureStore } from "@reduxjs/toolkit";
import plannerSlice from "../../feature/planner/plannerStore";

export default configureStore({
  reducer: {
    planner: plannerSlice,
  },
});

2

Answers


  1. You have a mistake in your reducer.

    You should use the action payload to retrieve the value you dispatch:

    export const plannerSlice = createSlice({
      name: "planner",
      initialState: {
        createDialogOpen: false,
      },
      reducers: {
        createDialogOpen: (state, action) => {
          state.createDialogOpen = action.payload;
        },
      },
    });
    
    Login or Signup to reply.
  2. The specific issue here is that the reducer is written incorrectly.

    You have:

    createDialogOpen: (state) => (value) => {
          state.createDialogOpen = value;
        },
    

    That means that it’s "a function that takes state as an argument, and returns a function that takes value as an argument".

    The result of a reducer is what it returns (or in the case of RTK + Immer, what you "mutate" in state). So, the problem here is that you are returning a function, and functions are not serializable.

    The other issue is that we don’t use value to describe any of the arguments to a reducer. The arguments are (state, action), and with createSlice, what normally matters is the action.payload field.

    As noted in the other comment, the correct syntax would be:

        createDialogOpen: (state, action) => {
          state.createDialogOpen = action.payload;
        },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search