Skip to content

Instantly share code, notes, and snippets.

View trblackw's full-sized avatar

Tucker Blackwell trblackw

View GitHub Profile
{
op: 'replace', //operations
path: [2, 'emailConfirmed'], //[index of updated value, property that was updated]
value: true, //updated value
}
import { produceWithPatches } from "immer"
const [nextState, patches, inversePatches] = produceWithPatches((draft, confirmedUserId) => {
draft[draft.findIndex(({ id }) => id === confirmedUserId)].emailConfirmed = true
})
import { useImmer } from "use-immer"
const [users, setUsers] = useImmer([
{ id: 1, name: "Bob", age: 24, emailConfirmed: false },
{ id: 2, name: "Sarah", age: 30, emailConfirmed: true },
{ id: 3, name: "Kevin", age: 20, emailConfirmed: false },
])
//when updating a user
setUsers(draft => {
draft[draft.findIndex(({ id }) => id === confirmedUserId)].emailConfirmed = true
const updateUsers = produce((draft, confirmedUserId) => {
draft[draft.findIndex(({ id }) => id === confirmedUserId)].emailConfirmed = true
})
onClick={() => setUsers(prev => updateUsers(prev, user.id))}
import produce from "immer"
const updateUsers = (state, confirmedUserId) => {
//users will be user state defined above
return produce(state, draft => {
draft[draft.findIndex(({ id }) => id === confirmedUserId)].emailConfirmed = true
})
}
//confirmedUserId derived from email confirmation
setUsers(prevState => prevState.map(user => (user.id === confirmedUserId ? { ...user, emailConfirmed: true } : user)))
const [users, setUsers] = useState([
{ id: 1, name: "Bob", age: 24, emailConfirmed: false },
{ id: 2, name: "Sarah", age: 30, emailConfirmed: true },
{ id: 3, name: "Kevin", age: 20, emailConfirmed: false },
])
const initialFormState = {
email: "",
password: "",
valid: false,
}
function Form() {
const [form, setForm] = useState(initialFormState)
//when updating the password field
state.hobbies.push("reading")