Перейти к содержанию

Как сбросить состояние

Для возврата состояния к исходному значению можно использовать следующий шаблон.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
import { create } from 'zustand';

// define types for state values and actions separately
type State = {
    salmon: number;
    tuna: number;
};

type Actions = {
    addSalmon: (qty: number) => void;
    addTuna: (qty: number) => void;
    reset: () => void;
};

// define the initial state
const initialState: State = {
    salmon: 0,
    tuna: 0,
};

// create store
const useSlice = create<State & Actions>()((set, get) => ({
    ...initialState,
    addSalmon: (qty: number) => {
        set({ salmon: get().salmon + qty });
    },
    addTuna: (qty: number) => {
        set({ tuna: get().tuna + qty });
    },
    reset: () => {
        set(initialState);
    },
}));

Сброс нескольких хранилищ одновременно

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
import { create as _create } from 'zustand';
import type { StateCreator } from 'zustand';

const storeResetFns = new Set<() => void>();

const resetAllStores = () => {
    storeResetFns.forEach((resetFn) => {
        resetFn();
    });
};

export const create = (<T extends unknown>() => {
    return (stateCreator: StateCreator<T>) => {
        const store = _create(stateCreator);
        const initialState = store.getState();
        storeResetFns.add(() => {
            store.setState(initialState, true);
        });
        return store;
    };
}) as typeof _create;

Сброс связанного хранилища с помощью шаблона Slices

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import create from 'zustand';
import type { StateCreator } from 'zustand';

const sliceResetFns = new Set<() => void>();

export const resetAllSlices = () => {
    sliceResetFns.forEach((resetFn) => {
        resetFn();
    });
};

const initialBearState = { bears: 0 };

interface BearSlice {
    bears: number;
    addBear: () => void;
    eatFish: () => void;
}

const createBearSlice: StateCreator<
    BearSlice & FishSlice,
    [],
    [],
    BearSlice
> = (set) => {
    sliceResetFns.add(() => set(initialBearState));
    return {
        ...initialBearState,
        addBear: () =>
            set((state) => ({ bears: state.bears + 1 })),
        eatFish: () =>
            set((state) => ({ fishes: state.fishes - 1 })),
    };
};

const initialStateFish = { fishes: 0 };

interface FishSlice {
    fishes: number;
    addFish: () => void;
}

const createFishSlice: StateCreator<
    BearSlice & FishSlice,
    [],
    [],
    FishSlice
> = (set) => {
    sliceResetFns.add(() => set(initialStateFish));
    return {
        ...initialStateFish,
        addFish: () =>
            set((state) => ({ fishes: state.fishes + 1 })),
    };
};

const useBoundStore = create<BearSlice & FishSlice>()(
    (...a) => ({
        ...createBearSlice(...a),
        ...createFishSlice(...a),
    })
);

export default useBoundStore;

CodeSandbox Demo

Источник — https://docs.pmnd.rs/zustand/guides/how-to-reset-state

Комментарии