Prep 11: Data Persistence
Textbook Reading
- JS
- MDN: data URLs
- MDN: FileReader
- MDN: Window: location and URLSearchParams
- MDN: encodeURIComponent() and decodeURIComponent()
Activity: Save and Load
In this activity, you’ll explore saving and loading files from JavaScript!
We’ve created a simple meal tracker application. Your job is to make it be able to save and load its data using JSON files.
Getting Started
Download the starter code here: meals.html
Instructions
1. Download JSON Functionality
Open this article: https://www.jameslmilner.com/posts/downloading-a-file-with-javascript/
Using it as a reference, implement the download button to:
- Put all the form data into an object
- Convert the object to a JSON string
- Make the browser download it as a
.jsonfile
2. Upload JSON Functionality
Open this article: https://javascript.info/file
Using it as a reference, implement the upload button to:
- Read the selected file from the file picker (this has been started for you)
- Parse the file’s text back into an object
- Fill in the form fields with the loaded data
Other Resources
Testing
- Fill in the meal form with your selections
- Click “Download JSON” to save your data
- Refresh the page (or clear the form)
- Use the file picker to select your saved JSON file
- Click “Upload JSON” to restore your data
- Click “Calculate Calories” to verify the graph displays correctly
Submission
Submit your completed meals.html file.