Getting an error “A non-serializable value was detected in the state” when using redux toolkit – but NOT with normal redux

Getting an error “A non-serializable value was detected in the state” when using redux toolkit – but NOT with normal redux

If you are using Redux Toolkit and encountering the error message “A non-serializable value was detected in the state” while normal Redux doesn’t throw any error, you are not alone. This error typically occurs when you are trying to store non-serializable values in your Redux state, which is not allowed by default in Redux Toolkit.
Redux Toolkit is a powerful library that simplifies the process of working with Redux by providing a set of opinionated tools and best practices. One of the features of Redux Toolkit is the built-in createSlice function, which automatically generates action creators and reducers for you. However, it also introduces a strict mode by default that disallows storing non-serializable values in the state.
Here are a few solutions to resolve this error:

Solution 1: Serialize the non-serializable value

If you are storing a non-serializable value in your Redux state, you can serialize it before storing it. This can be done by converting the non-serializable value into a serializable format, such as JSON.


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

const initialState = {
  data: JSON.stringify({ name: 'John', age: 25 }),
};

const slice = createSlice({
  name: 'example',
  initialState,
  reducers: {
    // your reducers here
  },
});

export const { actions, reducer } = slice;
    

In this example, we are using JSON.stringify to convert the non-serializable object into a string before storing it in the state.

Solution 2: Configure the serializableCheck option

If you want to allow non-serializable values in your Redux state, you can configure the serializableCheck option of Redux Toolkit to ignore certain values. This can be useful if you have a specific use case where you need to store non-serializable values.


import { configureStore } from '@reduxjs/toolkit';

const store = configureStore({
  reducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredPaths: ['path.to.non.serializable.value'],
      },
    }),
});
    

In this example, we are configuring the serializableCheck option to ignore the path.to.non.serializable.value in the state. This allows you to store non-serializable values without triggering the error.

Solution 3: Use the createAsyncThunk function

If you are using Redux Toolkit’s createAsyncThunk function to handle asynchronous actions, you can wrap the non-serializable value in a createAsyncThunk action. This will ensure that the non-serializable value is handled correctly and won’t trigger the error.


import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';

const fetchUser = createAsyncThunk('user/fetchUser', async (userId, thunkAPI) => {
  const response = await fetch(`/api/users/${userId}`);
  const user = await response.json();
  return user;
});

const slice = createSlice({
  name: 'example',
  initialState,
  reducers: {
    // your reducers here
  },
  extraReducers: (builder) => {
    builder.addCase(fetchUser.fulfilled, (state, action) => {
      state.data = action.payload;
    });
  },
});

export const { actions, reducer } = slice;
    

In this example, we are using createAsyncThunk to fetch user data from an API. The non-serializable value is returned by the API and stored in the state without triggering the error.
By following these solutions, you should be able to resolve the “A non-serializable value was detected in the state” error when using Redux Toolkit. Remember to always ensure that your Redux state only contains serializable values to maintain the integrity of your application.


Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *