A helper to use immer as Solid.js Signal to drive state.
$ npm install solid-immer
Use createImmerSignal
to create a immutable signal. The second value of the tuple is the updater function, which accepts an immer producer function or a value as argument.
import { createImmerSignal } from "solid-immer";
function App() {
const [todos, setTodos] = createImmerSignal([
{
id: "Solid.js",
title: "Learn Solid.js",
done: true,
},
{
id: "Immer",
title: "Try Immer",
done: false,
},
]);
function handleToggle(id) {
setTodos((draft) => {
const todo = draft.find((todo) => todo.id === id);
todo.done = !todo.done;
});
}
function handleAdd() {
setTodos((draft) => {
draft.push({
id: "todo_" + Math.random(),
title: "A new todo",
done: false,
});
});
}
// etc
}
For the full demo see CodeSandbox.
The value of createImmerSignal
should not be a primitive.
import { createImmerSignal } from "solid-immer";
import { createSignal } from "solid-js";
createImmerSignal("string"); // TypeError
createSignal("string"); // Good