What are the steps for implementing persisting and rehydrating data in redux-toolkit?

After setting up the redux-persist with react-toolkit as recommended in the documentation, I found myself needing to perform some operation on rehydrate. Unfortunately, my attempts have been unsuccessful so far. Here is what I have tried:

...
import { REHYDRATE } from 'redux-persist'
...

const accessControl = createSlice({
  name: 'accessControl',
  initialState,
  reducers: {
    loginStart(state: AccessControlState) {
      state.isLoading = true
    },
    loginSucces(state: AccessControlState, action: PayloadAction<LoginResponsePayload>) {
      state.isAuthenticated = true
      state.token = action.payload.access_token
      state.isLoading = false
      state.error = null
    },
    loginFailed(state: AccessControlState, action: PayloadAction<string>) {
      state.isAuthenticated = false
      state.token = ''
      state.isLoading = false
      state.error = action.payload
    },
    logout(state: AccessControlState) {
      state.isAuthenticated = false
      state.token = ''
      state.isLoading = false
      state.error = null
    },
    [REHYDRATE]: (state: AccessControlState) => {
      console.log('in rehydrate')
    }
  }
})

Answer №1

createSlice takes the keys from the reducers object to create action type constants with the slice name as a prefix. For instance, you might have action types like accessControl/loginStart and accessControl/loginFailed.

The reason your rehydrate reducer isn't being called is because its action type constant is accessControl/persist/REHYDRATE, while redux-persist sends an action with the type persist/REHYDRATE.

To address this, it's recommended to place your rehydration logic in the extraReducers object of your slice. These reducers are designed to handle actions external to the slice without generating actions in the slice's actions property.

Here’s an example:

import { createSlice } from '@reduxjs/toolkit'
import { REHYDRATE } from 'redux-persist'

const accessControl = createSlice({
  name: 'accessControl',
  initialState,
  reducers: {
    // Your regular reducers
  },
  extraReducers: (builder) => {
    builder.addCase(REHYDRATE, (state) => {
      console.log('handling rehydration')
    });
  }
})

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

Customize Monaco Editor: Implementing Read-Only Sections

I am currently working on setting up the Monaco Editor so that specific sections of the text content are read-only. Specifically, I want the first and last lines to be read-only. See example below: public something(someArgument) { // This line is read-onl ...

Can someone explain how to create a Function type in Typescript that enforces specific parameters?

Encountering an issue with combineReducers not being strict enough raises uncertainty about how to approach it: interface Action { type: any; } type Reducer<S> = (state: S, action: Action) => S; const reducer: Reducer<string> = (state: ...

Error when casting Typescript await toPromise

I encountered the following issue: export class FloorManagerComponent implements OnInit { public meta = { list: [], building: Building, loading: true, }; constructor( private router: Router, private ac ...

Having trouble locating node_modules post deployment?

Although the title may lead you astray, please stay with me for a moment. I've created a basic Angular2 application in Visual Studio 2015 and have now deployed it to Azure. While having node_modules in the development environment worked perfectly fi ...

Utilizing Angular2 with Webpack in Visual Studio 2015

Is there a way to utilize Visual Studio 2015 alongside Webpack and Angular2? I have successfully created an Angular2 App with VS, but now that I've added Webpack to build my app, I would like to debug all of my code using IIS Express. I want to be abl ...

Using Angular 6 shortcodes in HTML

Is there a way to save an element in HTML as an alias for repeated use in Angular 6 without using *ngIf directive? For instance, consider the following code snippet: <dumb-comp [name]="(someObservable | async).name" [role]="(someObservable | a ...

Currently, I am utilizing version 6.10.0 of @mui/x-date-pickers. I am interested in learning how to customize the color and format of a specific component within the library

I'm currently using @mui/x-date-pickers version 6.10.0 and I need to customize the color and format for a specific section in the mobile view. How can I achieve this? I want to display the date as "May 31st" like shown in the image below. Is there a ...

Declaring TypeScript functions with variable numbers of parameters

Is it possible to define a custom type called OnClick that can accept multiple types as arguments? How can I implement this feature so that I can use parameters of different data types? type OnClick<..> = (..) => void; // example usage: const o ...

The test() function in JavaScript alters the output value

I created a simple form validation, and I encountered an issue where the test() method returns true when called initially and false upon subsequent calls without changing the input value. This pattern repeats with alternating true and false results. The H ...

Transforming a React class component into a functional component and incorporating an action creator within the useEffect hook

Currently, I am in the process of refactoring a class component into a functional component. One particular issue I am facing is whether to use an action creator inside useEffect() instead of componentDidMount(). My linter is flagging that I'm not pas ...

Tips for storing an array of ReplaySubjects in a single variable in an Angular application

I am looking to store several ReplaySubjects in a single array. Here is my code: public filteredSearch: ReplaySubject<any[]> = new ReplaySubject(1); this.filteredSearch[id].next(filter(somedata)); When I run this code, I encounter an error saying ...

Retrieve the value from an HTML class using Angular

The Person Object has a field called schoolId, but the School object (not shown here) contains the schoolName. I want to display the schoolName in the table data cell instead of the schoolId from the Person Object. How can I achieve this? <tr *ngFor=& ...

Uncovering redundant fields in TypeScript and detecting errors through type inference

Encountering an unusual edge case with the TS compiler regarding type inference. Surprisingly, the code snippet below (with commented lines intact) should trigger a compile error, but it doesn't. interface IReturned { theField?: string; } interfa ...

Enforce boundaries by constraining the marker within a specified polygon on a leaflet map

Currently, I am utilizing a leaflet map to track the user's location. The map includes a marker for the user and a polygon shape. My goal is to ensure that the user marker always stays within the boundaries of the defined polygon. In case the user mov ...

Dividing internal CRUD/admin panel from the live application

Currently developing a moderately complex react app with redux. We have a production version that meets our requirements and now we are working on an administrative area for a local version of the application. This local version will only have basic CRUD f ...

Tips on obtaining checkbox values other than "true"

Having trouble retrieving the values of selected checkboxes instead of displaying "Custom Category"? I've attempted to access the values and attributes with no success. I'm aiming to display the values of the selected checkbox. app.component.ht ...

Using React with Typescript and ie18next to fetch translations from an external API

In the past, I have experience working with i18next to load translations from static json files. However, for my current project, I need to load all translations from an API. How can I achieve this? Additionally, how can I implement changing the translat ...

I want to use Angular and TypeScript to play a base64 encoded MP3 file

I am attempting to play a base64 encoded mp3 file in an Angular application. I have a byteArray that I convert to base64, and it seems like the byte array is not corrupted because when I convert it and paste the base64 string on StackBlitz https://stackbli ...

Tips for successfully importing $lib in SvelteKit without encountering any TypeScript errors

Is there a way to import a $lib into my svelte project without encountering typescript errors in vscode? The project is building and running smoothly. import ThemeSwitch from '$lib/ThemeSwitch/ThemeSwitch.svelte'; The error message says "Canno ...

Signal a return type error when the provided element label does not correspond with an existing entity

I am working on a component that accepts three props: children (React elements), index, and label. The goal is for the component to return the child element at a specific index when index is passed, and to return the element with a specific label when la ...