React Native Redux Toolkit: Despite the state showing a non-serializable value, my object is confirmed to be serializable

I recently upgraded my traditional react-native with redux App to the modern redux-toolkit and encountered an error:

A non-serializable value was found in the state, in the path: `currentUserSessionData.data`. Value:, CurrentUserSessionData {
  "isOnboardingDone": false,
}, 
Please review the reducer(s) handling this action type: currentUserSessionDataSlice/get/pending.

This error is puzzling because the CurrentUserSessionData object is quite simple:

class CurrentUserSessionData {
    isOnboardingDone: boolean = false;
}

export default CurrentUserSessionData;

I'm convinced that it is serializable!

Also, isn't it odd that the error states: "Value:comma CurrentUserSessionData"? The comma after : seems out of place, and I never defined the pending extra reducer.


I initially suspected an error in the state or store definitions, and though I've extensively studied the documentation, I can't identify the issue!

The slice:

import {createAsyncThunk, createSlice} from '@reduxjs/toolkit'
import * as CurrentUserSessionDataRepository from '../services/CurrentUserSessionDataRepository';
import CurrentUserSessionData from "../models/CurrentUserSessionData";

export const currentUserSessionDataSlice = createSlice({
    name: 'currentUserSessionDataSlice',
    initialState: {
        data: new CurrentUserSessionData(),
    },
    reducers: {},
    extraReducers: build => {

        build.addCase(currentUserSessionDataGetAsync.fulfilled, (state, action) => {
            state.data = action.payload;
        });

    },
});

export const currentUserSessionDataGetAsync = createAsyncThunk(
    "currentUserSessionDataSlice/get",
    async () => {
        return await CurrentUserSessionDataRepository.getCurrentUserSessionData();
    }
)

The data repository:

import AsyncStorage from '@react-native-async-storage/async-storage';
import * as Logger from "./Logger";
import CurrentUserSessionData from "../models/CurrentUserSessionData";

const asyncStorageCurrentUserSessionDataKey: string = "currentUserSessionData";

export const getCurrentUserSessionData = async (): Promise<CurrentUserSessionData> =>
{

    Logger.logDebug('getCurrentUserSessionData');
    const sessionDataRaw = await AsyncStorage.getItem(asyncStorageCurrentUserSessionDataKey);

    if (sessionDataRaw) {
        return JSON.parse(sessionDataRaw) as CurrentUserSessionData;
    }

    return {
        isOnboardingDone: false
    };

};

The store:

import {configureStore} from "@reduxjs/toolkit";
import {combineReducers} from "redux";
import {currentUserSessionDataSlice} from "./currentUserSessionDataSlice";
import {TypedUseSelectorHook, useDispatch, useSelector} from "react-redux";

const appStateStore = configureStore({
    reducer: combineReducers({
        currentUserSessionData: currentUserSessionDataSlice.reducer,
        // ....
    })
});

export default appStateStore;
export type IRootState = ReturnType<typeof appStateStore.getState>;
export type IAppDispatch = typeof appStateStore.dispatch;
export const useAppDispatch = () => useDispatch<IAppDispatch>();
export const useAppSelector: TypedUseSelectorHook<IRootState> = useSelector;

How I dispatch:

import {useAppDispatch} from "./appStateStore/appStateStore";
// ...
const dispatch = useAppDispatch();
await dispatch(currentUserSessionDataGetAsync());
// ...

What could be the issue here?

Answer №1

A common issue arises when attempting to serialize a class, as class instances are not fully serializable. In the context of writing a React+Redux app, it is recommended to use plain JS objects instead of actual classes.

For example, rather than initializing data with a class instance like this:

    initialState: {
        data: new CurrentUserSessionData(),
    },

You can simply use a plain JS object like this:

    initialState: {
        data: {isOnboardingDone: false}
    },

Additionally, it's worth noting that you can leverage configureStore to automatically call combineReducers instead of doing it manually.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I take to troubleshoot the ParseError related to the restriction of using 'import' and 'export' exclusively with 'sourceType: module' for importing UpgradeAdapter?

I have been working on upgrading an angular.js app to angular 2, following the guidelines provided at https://angular.io/docs/ts/latest/guide/upgrade.html. The application is already coded in Typescript, and we are using browserify and tsify for compiling ...

I'm looking to find the Angular version of "event.target.value" - can you help me out?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/pages/home/home.component.html I am currently working on getting the dropdown menu to function properly for filtering the flags displayed below it. My initial thought was to replicate the search ...

Implementing JavaScript Code in TypeScript

Every JavaScript code should also be valid in TypeScript, but when attempting to run the following code snippet below, an error is triggered. Could someone convert this JavaScript code into TypeScript? Error: 20:9 - TS2531 Error: Object is possibly 'z ...

Tips for Sending an Array of Objects to a Component

I am facing an issue with rendering specific data from an array of objects. Here is a snippet of the array: { "_id": { "$oid": "5f15d92ee520d44421ed8e9b" }, "image": "", "brand": " ...

Detect when the Keyboard is hidden in React Native

On my screen, I have a date picker and a text input. In order to prevent awkward transitions, I need to hide the keyboard before displaying the date picker. Currently, I'm resorting to a workaround because I don't know how to trigger a callback ...

Issue with DevExtreme nested table not expanding when sorting the parent table

Utilizing the DevExtreme Nested Data Grid (dx-data-grid) within an Angular app to exhibit hierarchical data is proving challenging for me. The data structure comprises a parent table, where each row can have child rows, which in turn can have grandchild ro ...

Why is there a discrepancy between the value displayed in a console.log on keydown and the value assigned to an object?

As I type into a text box and log the keydown event in Chrome, I notice that it has various properties (specifically, I'm interested in accessing KeyboardEvent.code). Console Log Output { altKey: false bubbles: true cancelBubble: false cancelable: t ...

Tips for updating the display after making an angular $http request using rxjs Observables

I have a project where I am utilizing angular's $http service to fetch data from a remote endpoint. I am keen on incorporating rxjs Observables, hence the call in my service is structured as follows: userInfo() : Rx.Observable<IUserInfo> { ...

Angular: Issue with subscribed variable visibility on screen

I am currently developing user management functionality. When a button is clicked, the goal is to save a new user and display an incoming password stored in the system. Below is a snippet of my code: onClick() { /*Code to populate the newUser variable from ...

The functionality of translations within a TypeScript object is currently malfunctioning

I am facing a perplexing issue with my code. I am utilizing lingui for internationalization in my application. The translations are stored using the `t` macro in a TypeScript object, which can be found here: https://github.com/Flaburgan/disco2very/blob/mas ...

Transform object into data transfer object

Looking for the most efficient method to convert a NestJS entity object to a DTO. Assuming the following setup: import { IsString, IsNumber, IsBoolean } from 'class-validator'; import { Exclude } from 'class-transformer'; export clas ...

Steps for creating a table with a filter similar to the one shown in the image below

https://i.sstatic.net/zR2UU.png I am unsure how to create two sub-blocks within the Business A Chaud column and Potential Business Column. Thank you! I managed to create a table with input, but I'm struggling to replicate the PUSH & CtoC Column for ...

Enhancing Performance of Data Switching in React Native Flatlist

I am working on a page that features a flat list with a toggle option between current events and past events data sets. These two sets of data will occupy the same user interface but will not be displayed simultaneously. Both sets of data will be loaded a ...

Redux's 'connect' function fails to recognize changes in the state array

I've recently implemented redux with a reducer that handles an array of time slots for a specific date. Whenever the date is changed, the reducer successfully updates the state (confirmed through console logs in my mapStateToProps function). However, ...

The data type 'string' cannot be assigned to the data type 'Position'

Currently, I am in the process of converting React js to typescript. The component being used is a Class Component. I would like to obtain CSS settings through props and apply them to an element. How can I resolve this issue? render(){return( <span st ...

Errors with the email composer in Ionic 3 displaying "plugin_not_installed" issue

Currently utilizing this feature within my Ionic 3 application. The plugin has been successfully installed, and the cordova-plugin-email-composer folder is present in the plugins directory. Despite multiple attempts of uninstalling and reinstalling, an err ...

Standing alone, an argument can never be fully validated without

Recently, while delving into the valuable resource titled Effective TypeScript by Dan Vanderkam, I stumbled across an intriguing scenario that left me puzzled. Within a code snippet presented in the book, there was a line - shape; that seemed perplexing ...

Declaration files for Typescript ESLint configurations

I've been researching this issue online, but I haven't been able to find any solutions. It could be because I'm not entirely sure what's causing the problem. What I'm trying to do is set a global value on the Node.js global object ...

Can you please provide a step-by-step guide for using socket.io with TypeScript and webpack, after installing it

Currently, I am experimenting with TypeScript in conjunction with node.js, socket.io, and webpack. To facilitate this setup, I have configured the webpack.config.js, tsconfig.json, and tsd.json files. Additionally, I acquired the typings file for socket.i ...

Understanding the complexity of defining the type of a function can be challenging. If you're tasked with a complicated function, determining its type

Let's break it down: Dict is defined as { [key: string]: () => any } The desired return value is represented by X I am attempting to create a type for a function that: Takes in a dictionary Dict T Returns an X Now, X also functions as a functio ...