-
-
Notifications
You must be signed in to change notification settings - Fork 105
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feature request: createActions utility #119
Comments
For your case it is a good solution. But I want to wait a little before adding it to the core to have more use cases. |
Thank you for your comment. :) I understand. People can use the utility, if they want. Just copy and paste the code. I also created alternative API and want to share. It just wrap store. Exampleexport const todoListStore = atom<TodoT[]>([]);
export const actions = createActions(todoListStore, {
addTodo(store, content: string) {
if (content.length === 0) return;
const newTodo = {
id: generateId(),
content,
isCompleted: false,
};
store.set([...store.get(), newTodo]);
},
completeTodo(store, id: TodoT["id"], isCompleted: boolean) {
store.set(store.get().map((todo) =>
todo.id === id ? { ...todo, isCompleted } : todo
));
},
changeTodo(store, id: TodoT["id"], content: string) {
store.set(store.get().map((todo) => (todo.id === id ? { ...todo, content } : todo)));
},
deleteTodo(store, id: TodoT["id"]) {
store.set(store.get().filter((todo) => todo.id !== id));
},
}); implementationexport type WrapAction<SomeStore extends WritableStore, I extends Record<string, (store: SomeStore, ...args: any[]) => void>> = {
[K in keyof I]: I[K] extends (store: SomeStore, ...args: infer A) => void ? (...args: A) => void : never
}
function createActions<
SomeStore extends WritableStore,
I extends Record<string, (store: SomeStore, ...args: any[]) => void>
>(store: SomeStore, rawActions: I): WrapAction<SomeStore, I> {
const result: any = {};
for (const name in rawActions){
result[name] = action(store, name, rawActions[name]);
}
return result as WrapAction<SomeStore, I>;
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
TL:DR
I made createActions utility like redux-toolkit's createSlice. TypeScript ready with Type Inference.
Problem
It takes a long time to create multiple actions.
There are many boilerplates now. Like next TodoList example.
Did you find the duplicated pattern here?
Solution
So I made createActions utility like redux-toolkit's createSlice but simple.
Here it is:
It is Typescript ready, and can inference types well. Thanks to @XiNiha
Implementation
It is simple, but just a proof of concept.
It can be imperative, but encapsulate effect in the function...
Limitation
setKey
andnotify
.The text was updated successfully, but these errors were encountered: