Ramda's pipe could be use to remove simplify middlewares #224
Replies: 3 comments 13 replies
-
Thanks for opening up a discussion. Some questions in my mind are:
|
Beta Was this translation helpful? Give feedback.
-
How should I add persist from zustand middleware using both log and immer from the same example? Is it possible or I should make it manual because of persist's configuration? |
Beta Was this translation helpful? Give feedback.
-
I'm sharing an alternative approach I created, where I define a reusable type called Here's the middleware setup: type WithMiddleWare<T, Mos extends [StoreMutatorIdentifier, unknown][] = []> = (
initialzer: StateCreator<T, Mos>,
) => UseBoundStore<StoreApi<T>>;
const createBearStore: WithMiddleWare<
BearState,
[['zustand/persist', unknown], ['zustand/devtools', unknown], ['zustand/immer', unknown]]
> = pipe(
immer,
(initializer) => devtools(initializer, { name: 'todo' }),
(initializer) => persist(initializer, { name: 'todo-storage', storage: createJSONStorage(() => localStorage) }),
create(),
); And here's the full working example: import { pipe } from 'ramda';
import { create, type StateCreator, type StoreApi, type StoreMutatorIdentifier, type UseBoundStore } from 'zustand';
import { createJSONStorage, devtools, persist } from 'zustand/middleware';
import { immer } from 'zustand/middleware/immer';
type WithMiddleWare<T, Mos extends [StoreMutatorIdentifier, unknown][] = []> = (
initialzer: StateCreator<T, Mos>,
) => UseBoundStore<StoreApi<T>>;
interface BearState {
bears: number;
increasePopulation: () => void;
removeAllBears: () => void;
}
const createBearStore: WithMiddleWare<
BearState,
[['zustand/persist', unknown], ['zustand/devtools', unknown], ['zustand/immer', unknown]]
> = pipe(
immer,
(initializer) => devtools(initializer, { name: 'bear' }),
(initializer) => persist(initializer, { name: 'bear-storage', storage: createJSONStorage(() => localStorage) }),
create(),
);
export const useBearStore = createBearStore((set) => ({
bears: 0,
increasePopulation: () => set((state) => ({ bears: state.bears + 1 }), false, 'increasePopulation'),
removeAllBears: () => set({ bears: 0 }, false, 'removeAllBears'),
})); |
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
To be honest I fell in love the first time that I used ramda and I feel like the pipe method could add a lot of value to zustand, you can add as many middlewares as you wish as long as create is the last argument.
I would love to open some discussion about how this behavior could be added as a own feature. (It's an overkill to add ramda just to use pipe)
Beta Was this translation helpful? Give feedback.
All reactions