react-apollo-autosave
A React component that allows for editing and autosave behavior, combining an Apollo Query and Mutation. With the query, you retrieve the data that you want to edit from your backend. The mutation updates it. Internally, the component maintains a local copy of the data so that you can directly couple properties of the data to React props. As a result, you don't need to create variables inside your component state for this.
Installation
npm install react-apollo-autosave --save
Example
; // GraphQL query and mutation for reading and updating a user's name; ; // A simple React component that shows an input where you can edit a user's name
Features
Autosaving changes
Whenever you change the value that the editor component controls, you call the update
method, which updates the local data. The component then automatically calls the mutate function (resulting in the autosave behavior). The component uses the lodash throttle
function to reduce the number of queries to the backend. You can set the throttle wait time and whether the throttle is leading or trailing by changing the waitTime
(default 3000 ms) and throttleType
(default "leading") properties.
Explicit saving
If you want control over the saving behavior (for example only save when the user presses a button), you can set the mutateOnUpdate
prop to false
. Whenever the input changes, call the update
function:
update;
When the user presses the save button, call the update
function again to trigger a save explicitly:
updateundefined, , true;
Combining with validation
In case of an invalid input, normally you don't want to sync the changes to the backend, but you do want to change the local data, otherwise the user will not be able to see what (s)he is typing/clicking on. To support validation, you can override whether a mutation should happen when you call the update
function (see the code example in the previous section).