Lifecycle basics: save and load
This page shows how to use Sercrod’s built-in
*save and *load directives.
They let you download your data as a JSON file and load it back later.
1. A small note editor
Start with a tiny host that keeps one field called note:
<serc-rod data='{"note":"Type something here..."}'>
<p>Your note:</p>
<textarea *input="note"></textarea>
</serc-rod>
The *input="note" directive binds the textarea to
the note field. As you type, the data changes.
2. Download the data as JSON (*save)
Next, add a button with *save. When you click it,
Sercrod downloads a JSON file from the current data.
<serc-rod data='{"note":"Type something here..."}'>
<p>Your note:</p>
<textarea *input="note"></textarea>
<p>
<button type="button" *save="note">Download JSON</button>
</p>
</serc-rod>
Here *save="note" means “save only the
note field” into the JSON file. Without any value
(for example just *save) Sercrod would save the
entire data object.
3. Load the JSON back (*load)
Now add a *load button. It opens a file dialog,
reads the JSON, and merges it back into the data.
<serc-rod data='{"note":"Type something here..."}'>
<p>Your note:</p>
<textarea *input="note"></textarea>
<p>
<button type="button" *save="note">Download JSON</button>
<button type="button" *load="note">Load JSON</button>
</p>
</serc-rod>
Both *save="note" and *load="note"
use the same field list. The JSON file only needs to contain
that field. When you choose the file, Sercrod parses it and
applies the values, then re-renders the host.
4. Try it live
Below is the same example, running on this page.
Sample
Your note:
Type in the box, download the JSON, then reload it to restore the same text.
Extra: using localStorage
Instead of downloading a JSON file, you can also keep a small
note across reloads with localStorage.
Code
<serc-rod data='{"note":"", "status":""}'>
<p>Type a short note and keep it in this browser:</p>
<textarea *input="note"></textarea>
<p>
<button type="button" @click="localStorage.setItem('sercrod_note', note); status = 'Saved to localStorage.'">
Save
</button>
<button type="button" @click="note = localStorage.getItem('sercrod_note') || ''; status = note ? 'Loaded from localStorage.' : 'Nothing saved yet.'">
Load
</button>
</p>
<p *if="status">%status%</p>
</serc-rod>
Sample
Type a short note and keep it in this browser:
%status%
This keeps the data in the current browser only. It does not create files, and clearing site data will remove the note.
Next
You have seen how to move data in and out of Sercrod using files. In the next step, you can combine this with other lifecycle tools and server APIs.