Issue with updating initial state that is null in Redux Toolkit

Encountered an issue while using Redux Toolkit with Redux Persist. Unable to update the initial state of a user if it's null. The code consistently assigns null to the store regardless of passing parameters.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { IUser, Nullable } from "../../types";

const initialState = null as Nullable<IUser>  

export const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        set(state, action: PayloadAction<IUser>){
            state = action.payload
        }
    }
})

export default userSlice.reducer;

However, when the initial state is structured as shown below, everything functions correctly. Curious as to why this is the case.

const initialState = {
    user: null as Nullable<IUser>  
}

Answer №1

It is implemented in this way because the initial state dictates whether subsequent states should also be of the same type. If the initial state is a reference type/object, then all following states must also be reference types/objects. Conversely, if the initial state is a primitive type or null, then the following state(s) must be of primitive type.

When faced with an initially undefined/null object, my approach usually looks like this:

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

const userSlice = createSlice({
  name: "user",
  initialState: {
    value: undefined
  },
  reducers: {
    setUser: (state, action) => {
      state.value = action.payload;
    },
  },
});

export const { setUser } = userSlice.actions;

export const userReducer = userSlice.reducer;

Answer №2

After much deliberation, I finally managed to complete this task. However, I am not entirely sure if my solution is the most appropriate one.

import { createSlice, PayloadAction } from "@reduxjs/toolkit";
import { Nullable, User } from "../../../types";

const initialState = null as Nullable<User>;

export const userSlice = createSlice({
    name: 'user',
    initialState: initialState,
    reducers: {
        set(state, action: PayloadAction<User>){
            return state ? {...state, ...action.payload} :  action.payload;
        },
        setToken(state, action: PayloadAction<User['token']>){
            state && (state.token = action.payload)
        },
        setUsername(state, action: PayloadAction<User['username']>){
            state && (state.username = action.payload)
        },
        unset(){
            return initialState
        }
    }
})

export default userSlice.reducer;

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

Creating, editing, and deleting data in Ng2 smart table is a seamless process that can greatly enhance

While working on my Angular 2 project, I utilized [ng2 smart table]. My goal was to send an API request using the http.post() method. However, upon clicking the button to confirm the data, I encountered the following error in the console: ERROR TypeErro ...

Prevent methods from being called in a Typescript class after they have already

I encountered a scenario where I need to exclude certain methods from the return type of a class method once they have been called. Consider a class named Setup with methods step1, step2, and step3. class Setup { step1() { return this; } ...

Tips for picking out a particular item from a list of child elements

When I select the first parent's children array, it ends up selecting every other parent's children as well. This is due to index 0 remaining the same for all of them. How can I specify and highlight a specific child? Link: Check out the stackb ...

Error message: The "spawn" function is not defined and is causing a TypeError to be thrown in

Having a bit of trouble here. I'm trying to make an async request using redux-thunk in my action creator, and the code looks like this: export const downloadFromYoutube = (download) => { console.log("Hello"); return dispatch => { va ...

Using useRef as a prop in React with TypeScript

I am currently experimenting with TypeScript and encountering an issue when trying to use useRef in a custom element specifically when passing it as a prop I have attempted the following: import React from "react"; export interface InputProps extends ...

The challenge of generics in Typescript: destructuring and spreading

I am facing an issue with destructing parameters and creating a new object of the same type in Typescript. The following code functions properly: function customFunc<T extends { attribute: string }>(parameter: T): T { const { ...rest } = paramete ...

Guide to developing a private shared Node.js module using TypeScript

I have a unique idea for a nodejs server service, consisting of: a REST API, and various asynchronous workers. My vision is to separate these components into different subnets and git repositories while still enabling them to access the same database en ...

The perplexing actions of Map<string, string[]> = new Map() have left many scratching their heads

I encountered an issue while trying to add a value to a map in my Angular project. The map is initially set up using the following code: filters: Map<string, string[]> = new Map(); However, when I attempt to add a value to this map, it starts displa ...

Checking the text both before and after clicking a link by using a method such as content verification

Currently, I am encountering an issue with validating the text on my links before and after they are clicked. If the link text reads "one two" before clicking and remains as "one two" after the click, then the test case passes. However, if the text change ...

Incorporate a new method into a TypeScript class from a separate file

I'm curious about the feasibility of adding additional functions to a class prototype in Typescript. Here's my dilemma: I have a file containing a class, for example image.ts: export class Image { b64img: string; } Since this class is gene ...

How is it possible to leverage the CDN URL mechanism for package management when working with Typescript?

Is it possible to use a CDN URL pointing mechanism to resolve packages in Typescript? One example is the Material Icon package installation, which can be included using the following code: <link rel="stylesheet" href="https://fonts.googleapis.com/icon? ...

Executing a Prisma query with a selection

My Prisma models involve User, Car, and Reservation entities: model User { id String @id @default(auto()) @map("_id") @db.ObjectId name String? email String? @unique emailVerified DateTime? image ...

Create a keyup function that triggers an alert message if the user's input does not meet the

Hello, I'm looking for some assistance with a coding problem. Basically, I have an array of numbers which includes 5, 8, and 10. I need to create a form where users can input numbers. If the user inputs a number that is not 5, 8, or 10, I want to disp ...

Verifying callback type in Typescript based on another argument's validity

There is a JavaScript function that I am working with: const fn = (cb, param) => { cb(param); }; This function is meant to be called in two ways within TypeScript: const cb0 = () => {}; fn(cb0); const cb1 = (param: string) => { }; fn(cb1, &a ...

The babel tool is unable to identify ... when it comes to syntax. (Redux)

Whenever I try to run Webpack with Babel, I encounter an issue where Babel can't convert the code in my Redux reducer. Here is the error message that I keep receiving: ERROR in ./src/reducers/api_reducer.js Module build failed: SyntaxError: Unexpecte ...

Passing values in onPress method of TouchableOpacity without using arrow functions or bind function can be achieved by using JSX props. Remember not to use arrow functions in JSX props

I am working on a React Native project and I have a TouchableOpacity component in my view with an onPress method. I want to avoid using arrow functions and bind functions in the onPress method as it creates a new function every time. My goal is to pass par ...

Having trouble utilizing the DatePicker component in my react native application

I've encountered an issue while using DatePicker in react native. Whenever I try to use it, an error pops up saying: "render error a date or time must be specified as value prop". Here is the link to my repository: my github repository const [date, se ...

Exploring Several Images and Videos in Angular

I'm experiencing a challenge with displaying multiple images and videos in my Angular application. To differentiate between the two types of files, I use the "format" variable. Check out Stackblitz export class AppComponent { urls; format; on ...

What could be causing the undefined value in my Many-to-Many relationship field?

Currently, I am in the process of setting up a follower/following system. However, as I attempt to add a new user to the following list, I encounter an error stating Cannot read property 'push' of undefined. This issue results in the creation of ...

How can we avoid duplicating injectors in a child class when extending a class that already has injected services?

Delving deep into TypeScript inheritance, particularly in Angular 11, I've created a BasePageComponent to encompass all the necessary functions and services shared across pages. However, I've encountered an issue where my base class is becoming b ...