On the previous page we learned how to set up conflict-free data storage with an initial value—let’s learn how to modify storage by taking this and transforming it into a collaborative form.
Currently, our storage consists of a LiveObject
called person
. Storage
itself is also always a LiveObject
.
Storage: { person: LiveObject<{ name: string; age: number; }>;}
To access person
, we must first retrieve it from our storage with
LiveObject.get
. We can then modify a property on person
with
LiveObject.set
.
const person = storage.get("person");person.set("name", "Albert");
But how do we access our storage in the first place?
We can add the useMutation
hook to access our storage. This hook works
similarly to useCallback
from
React, however it also gives you access to your mutable storage.
const updateName = useMutation(({ storage }) => { const person = storage.get("person"); person.set("name", "Albert");}, []);
Like with useCallback
,
remember to place any dependencies in the array.
We can also provide arguments to useMutation
, for example to allow any
name
to be used. Try adding this code snippet to Room.tsx
.
/Room.tsx
// Add mutationconst updateName = useMutation(({ storage }, newName: string) => { const person = storage.get("person"); person.set("name", newName);}, []);
This function can then be called with a name
argument.
updateName("Grace");
To create an input in a collaborative form, we can combine the value returned
from useStorage
to display the value, and useMutation
to modify it.
/Room.tsx
return ( <input type="text" value={person.name} onChange={(e) => updateName(e.target.value)} />);
Update the return value in Room.tsx
to see a working realtime input!
Think you’ve got it? Try adding a second input for age
!