Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/docs-website/astro.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ export default defineConfig({
{ label: 'Migrations with Redux Remigrate', slug: 'usage/migrations' },
{ label: 'Custom Storage Driver', slug: 'usage/custom-storage-driver' },
{ label: 'Using in Reducers', slug: 'usage/using-in-reducers' },
{ label: 'Lazy-loaded Reducers', slug: 'usage/lazy-loaded-reducers' },
{ label: 'Rehydration Gate', slug: 'usage/rehydration-gate' },
{ label: 'Error Handling', slug: 'usage/error-handling' },
{
Expand Down
2 changes: 1 addition & 1 deletion packages/docs-website/src/content/docs/api/actions.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ Redux Remember dispatches these actions that you can listen to in your reducers.
- **Type:** `'@@REMEMBER_REHYDRATED'`
- **Description:** Dispatched when state has been loaded from storage
- **Payload:** The complete rehydrated root state
- **Timing:** Dispatched once when the application loads
- **Timing:** Dispatched once when the application loads — and again on every [`store.unsafeRehydrate()`](./remember-enhancer.md#storeunsaferehydrate) call, if you use it

## REMEMBER_PERSISTED

Expand Down
22 changes: 22 additions & 0 deletions packages/docs-website/src/content/docs/api/remember-enhancer.md
Original file line number Diff line number Diff line change
Expand Up @@ -193,6 +193,28 @@ rememberEnhancer(window.localStorage, rememberedKeys, {
- Type: `StoreEnhancer`
- Description: A Redux enhancer to be used with your store

## Store Methods

### store.unsafeRehydrate

- **Type:** `(keys?: string[]) => Promise<void>`
- **Description:** Reads the given keys from storage, rehydrates them into the store, and adds them to the remembered set so they are persisted from then on. Called with no arguments, it re-reads every currently remembered key.
- **Use Case:** Rehydrating a [lazy-loaded (injected) reducer](../usage/lazy-loaded-reducers.md) whose key was not known when the store was created
- **Why "unsafe":** It dispatches [`REMEMBER_REHYDRATED`](./actions.md#remember_rehydrated) again, which the rest of the documentation describes as happening exactly once, and it overlays whatever is in storage on top of live state. Both are fine when you call it deliberately, right after injecting a reducer; neither is safe on a timer or in response to arbitrary events.
- **Notes:**
- [`migrate`](#migrate) is **not** applied. It is a whole-state, run-once function, and re-running it over already-migrated state would corrupt it. If the lazy slice's stored data needs migrating, migrate it inside its own `unserialize`.
- If the read fails, the error goes to [`errorHandler`](#errorhandler), no action is dispatched, and the keys are **not** added to the remembered set — so a transient storage failure cannot cause the slice's initial state to be written over good stored data.
- The returned promise resolves once the state has been rehydrated, so you can `await` it before rendering the lazy route.
- With [`initActionType`](#initactiontype) set, call it only after that action has been dispatched. Before then Redux Remember is disabled, and the initial rehydration would later overwrite what you loaded.

**Example:**
```ts
rootReducer.inject(lazyPersistedSlice);
await store.unsafeRehydrate(['lazyPersisted']);
```

See [Lazy-loaded Reducers](../usage/lazy-loaded-reducers.md) for the full walkthrough.

## See Also

- [rememberReducer](./remember-reducer.md) - Wrap your reducers
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
---
title: Lazy-loaded (injected) reducers
---

Redux Remember supports lazy-loaded / injected reducers — reducers you add to the store after it's been created, for example a code-split slice that loads when the user navigates to a route. There are two cases, depending on whether the injected slice is persisted.

## Non-persisted injected slices

If an injected slice is not persisted (its key isn't in `rememberedKeys`), there's nothing special to do. Pass a dynamic root reducer — for example Redux Toolkit's [`combineSlices`](https://redux-toolkit.js.org/api/combineSlices) — to `rememberReducer`, and inject whenever you like:

```ts
import { configureStore, combineSlices } from '@reduxjs/toolkit';
import { rememberReducer, rememberEnhancer } from 'redux-remember';

const rootReducer = combineSlices(baseSlice);

const store = configureStore({
reducer: rememberReducer(rootReducer),
enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(
// the lazy slice's key is deliberately NOT listed here
rememberEnhancer(window.localStorage, ['base'])
),
});

// later, on demand:
rootReducer.inject(lazySlice);
```

Redux Remember only ever touches the keys listed in `rememberedKeys`, so an injected slice that isn't listed is invisible to it — no rehydrate, no persist.

## Persisted injected slices

For a slice you *do* want persisted, timing matters. Redux Remember reads storage and dispatches [`REMEMBER_REHYDRATED`](../api/actions.md#remember_rehydrated) once, when it initializes. A reducer injected after that point has already missed its rehydration, so its stored value would be dropped and it would start from its initial state.

Call [`store.unsafeRehydrate(keys)`](../api/remember-enhancer.md#storeunsaferehydrate) after injecting the reducer. It reads those keys from storage, rehydrates them into the store, and adds them to the remembered set so they're persisted from then on:

```ts
const rootReducer = combineSlices(baseSlice);

const store = configureStore({
reducer: rememberReducer(rootReducer),
enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(
rememberEnhancer(window.localStorage, ['base'])
),
});

// when the lazy slice loads:
rootReducer.inject(lazyPersistedSlice); // 1. add the reducer to the tree
await store.unsafeRehydrate(['lazyPersisted']); // 2. load its persisted state
```

After this, `lazyPersisted` holds its stored value and is persisted on every change like any statically-defined key. Called with no arguments, `store.unsafeRehydrate()` re-reads every currently remembered key.

## Why "unsafe"?

The method is named `unsafeRehydrate` because it does two things the rest of Redux Remember does not:

- It dispatches [`REMEMBER_REHYDRATED`](../api/actions.md#remember_rehydrated) again, which is otherwise documented as happening exactly once per store. Reducers that flip a one-way flag (such as a [Rehydration Gate](./rehydration-gate.md)) will see it a second time.
- It overlays whatever is in storage on top of live state. That is exactly what you want immediately after injecting a reducer, and it is not what you want in response to arbitrary events.

Within those bounds it is safe by construction:

- Actions dispatched while storage is being read are **not** rolled back — the state is re-read after the load, immediately before dispatching.
- Concurrent calls do not revert each other, so you can inject several lazy slices at once.
- A key only starts being persisted **after** its stored value has been loaded, so a slow driver or a failed read can never cause the slice's initial state to overwrite good stored data.
- [`migrate`](../api/remember-enhancer.md#migrate) is not re-run. It is a whole-state, run-once function; if a lazy slice's stored data needs migrating, do it in that slice's `unserialize`.

Two things to keep in mind:

- Await the returned promise before rendering the lazy route, otherwise it renders with initial state and then jumps to the stored value.
- If you use [`initActionType`](../api/remember-enhancer.md#initactiontype), call `unsafeRehydrate` only after that action has been dispatched — before then Redux Remember is disabled, and the initial rehydration would later overwrite what you loaded.

## See Also

- [`rememberEnhancer`](../api/remember-enhancer.md) — the `rememberedKeys` option and the [`store.unsafeRehydrate`](../api/remember-enhancer.md#storeunsaferehydrate) method
- [`REMEMBER_REHYDRATED`](../api/actions.md#remember_rehydrated)
- [Using in Reducers](./using-in-reducers.md)
151 changes: 150 additions & 1 deletion packages/redux-remember/src/__tests__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { Options } from '../types.ts';

describe('index.ts', () => {
const mockRehydrate = {
loadKeys: vi.fn(),
rehydrateReducer: vi.fn(() => 'REHYDRATE_REDUCER')
};

Expand All @@ -14,6 +15,7 @@ describe('index.ts', () => {
let index: typeof indexModule;

beforeEach(async () => {
mockRehydrate.loadKeys = vi.fn(async () => ({}));
mockRehydrate.rehydrateReducer = vi.fn(() => 'REHYDRATE_REDUCER');
mockInit = vi.fn(() => {});
mockCombineReducers = vi.fn(() => {});
Expand Down Expand Up @@ -127,14 +129,20 @@ describe('index.ts', () => {
};

let mockCreateStore: StoreCreator;
const mockStore = 'my-mocked-store';
let mockStore: any;
const rememberedKeys = ['zz', 'bb', 'kk'];
const rootReducer = (state = {}) => state;
let rootReducerWrapper: Reducer;
const initialState = { myReducer: 'bla' };
const enhancer: any = 'dummy enhancer';

beforeEach(() => {
mockStore = {
name: 'my-mocked-store',
getState: vi.fn(() => ({})),
dispatch: vi.fn()
};

mockCreateStore = vi.fn((wrapper) => {
rootReducerWrapper = wrapper;
return mockStore;
Expand Down Expand Up @@ -258,5 +266,146 @@ describe('index.ts', () => {
vi.clearAllTimers();
vi.useRealTimers();
});

it('exposes store.unsafeRehydrate() and reads the requested keys', async () => {
const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, [...rememberedKeys]
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

expect(typeof store.unsafeRehydrate).toBe('function');

await store.unsafeRehydrate(['newKey']);

expect(mockRehydrate.loadKeys).toHaveBeenCalledWith(
['newKey'],
expect.objectContaining({
driver: mockDriver,
prefix: '@@remember-'
})
);
});

it('store.unsafeRehydrate() does not apply migrate()', async () => {
const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, [...rememberedKeys], { migrate: (state) => state }
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

await store.unsafeRehydrate(['newKey']);

// migrate() is a whole-state, run-once function - re-running it over
// already-migrated state would be unsound
const [, loadOptions] = mockRehydrate.loadKeys.mock.calls[0];
expect(loadOptions).not.toHaveProperty('migrate');
});

it('store.unsafeRehydrate() remembers new keys without mutating the caller array', async () => {
const callerKeys = ['aa', 'bb'];

const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, callerKeys
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

await store.unsafeRehydrate(['aa', 'cc']);

// the array the caller passed in is left alone
expect(callerKeys).toEqual(['aa', 'bb']);

// the store's own copy - shared with init() - gained 'cc' and did not
// duplicate 'aa', so 'cc' is persisted from now on
const [, storeKeys] = mockInit.mock.calls[0];
expect(storeKeys).toEqual(['aa', 'bb', 'cc']);
});

it('store.unsafeRehydrate() with no arguments re-reads every remembered key', async () => {
const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, ['aa', 'bb']
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

await store.unsafeRehydrate();

expect(mockRehydrate.loadKeys).toHaveBeenCalledWith(
['aa', 'bb'],
expect.objectContaining({ driver: mockDriver })
);
});

it('store.unsafeRehydrate() dispatches the state as of after the read', async () => {
mockStore.getState = vi.fn(() => ({ counter: 1 }));

// state moves on while storage is being read
mockRehydrate.loadKeys = vi.fn(async () => {
mockStore.getState = vi.fn(() => ({ counter: 2 }));
return { lazy: 'loaded' };
});

const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, ['counter']
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

await store.unsafeRehydrate(['lazy']);

// the payload must carry the post-read state, otherwise anything
// dispatched during the read is rolled back
expect(mockStore.dispatch).toHaveBeenCalledWith({
type: actionTypes.REMEMBER_REHYDRATED,
payload: { counter: 2, lazy: 'loaded' }
});
});

it('store.unsafeRehydrate() does nothing when the read fails', async () => {
mockRehydrate.loadKeys = vi.fn(async () => undefined);

const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, ['aa']
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

await store.unsafeRehydrate(['bb']);

expect(mockStore.dispatch).not.toHaveBeenCalled();

// 'bb' must not start being persisted - the next persist would write the
// slice's initial state over whatever is already in storage
const [, storeKeys] = mockInit.mock.calls[0];
expect(storeKeys).toEqual(['aa']);
});

it('store.unsafeRehydrate() waits for the initial rehydration', async () => {
let finishInit = () => {};
mockInit.mockImplementationOnce(() => new Promise<void>((resolve) => {
finishInit = resolve;
}));

const storeMaker: StoreCreator = index.rememberEnhancer(
mockDriver, ['aa']
)((() => mockStore) as StoreCreator);

const store: any = storeMaker(rootReducer, initialState, enhancer);

const pending = store.unsafeRehydrate(['bb']);
await Promise.resolve();

// init() is still loading - reading now would let its dispatch roll us back
expect(mockRehydrate.loadKeys).not.toHaveBeenCalled();

finishInit();
await pending;

expect(mockRehydrate.loadKeys).toHaveBeenCalledWith(
['bb'],
expect.objectContaining({ driver: mockDriver })
);
});
});
});
78 changes: 77 additions & 1 deletion packages/redux-remember/src/__tests__/rehydrate.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { describe, it, expect, beforeEach, afterEach, vi, type Mock } from 'vitest';
import type * as rehydrateModule from '../rehydrate.ts';
import { REMEMBER_REHYDRATED } from '../action-types.ts';
import type { Driver } from '../types.ts';
Expand Down Expand Up @@ -180,6 +180,82 @@ describe('rehydrate.ts', () => {
});
});

describe('loadKeys()', () => {
let mockPrefix: string;
let mockDriver: Driver;
let mockErrorHandler: Mock;

const exec = (keys: string[], opts = {}) => mod.loadKeys(
keys,
{
prefix: mockPrefix,
driver: mockDriver,
unserialize: (data) => JSON.parse(data),
persistWholeStore: false,
errorHandler: mockErrorHandler,
...opts
}
);

beforeEach(() => {
mockDriver = {
getItem: vi.fn((key) => JSON.stringify(`data-${key}`)),
setItem() {}
};

mockErrorHandler = vi.fn();
mockPrefix = 'pref2.';
});

it('reads the given keys one by one', async () => {
const res = await exec(['aa', 'bb']);

expect(mockDriver.getItem).toHaveBeenCalledWith('pref2.aa');
expect(mockDriver.getItem).toHaveBeenCalledWith('pref2.bb');

expect(res).toEqual({
aa: 'data-pref2.aa',
bb: 'data-pref2.bb'
});
});

it('reads the given keys out of the whole store', async () => {
mockDriver.getItem = vi.fn(() => JSON.stringify({
aa: 'val-aa',
bb: 'val-bb',
cc: 'val-cc'
}));

const res = await exec(['aa', 'cc'], { persistWholeStore: true });

expect(mockDriver.getItem).toHaveBeenCalledWith('pref2.rootState');

expect(res).toEqual({
aa: 'val-aa',
cc: 'val-cc'
});
});

it('returns an empty object when nothing is stored', async () => {
mockDriver.getItem = vi.fn(() => null);

expect(await exec(['aa'])).toEqual({});
});

it('returns undefined and reports the error when the read fails', async () => {
mockDriver.getItem = vi.fn(() => {
throw new Error('nope');
});

expect(await exec(['aa'])).toBeUndefined();

expect(mockErrorHandler).toHaveBeenCalledWith(
expect.objectContaining({ name: 'RehydrateError' })
);
});

});

describe('rehydrate()', () => {
let mockState = {};
const mockStore = {
Expand Down
Loading