Getting startedReact tutorial

//Modifying storage data

Modifying storage data

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.

Modifying storage

Currently, our storage consists of a LiveObject called person. Storage itself is also always a LiveObject.

type 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?

Adding a mutation

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");}, []);

We can also provide arguments to useMutation, for example to allow any name to be used. Try adding this code snippet to Room.tsx.

Modify the code in /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.


Creating a real-time input

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.

Modify the code in /Room.tsx
return (  <input    type="text"    value={}    onChange={(e) => updateName(}  />);

Update the return value in Room.tsx to see a working real-time input!