🖥 SvelteKit Session Storage: Cache Form Data #
Here we look at how you can use Session Storage in SvelteKit to cache form data temporarily. You might use this code on a form or on a page where a user can potentially enter a long piece of text. User's often run JavaScript blockers like NoScript to protect their privacy. A downside is when your site needs to run third party JavaScript in the process of submitting a form, the user might end up having to refresh their browser and lose the details they just entered. This happens because once the user enables the necessary JavaScript to load on the page, the plugin refreshes the window (so the previously blocked JavaScript actually loads). This can provide a frustrating user experience.
In this video, we see how you can use SvelteKit Session Storage to repopulate the form fields if the browser refreshes. We also see how to bind a form field to a JavaScript variable and finally how to clear data stored in Session Storage. If you think there's something in there for you to learn, then let's crank up the video and see how it all works!
📹 SvelteKit Session Storage: Video #
Please enable JavaScript to watch the video 📼
🗳 Poll #
🖥 SvelteKit Session Storage: Code #
src/routes/+page.svelte
— click to expand code.
1 <script>2 import { browser } from '$app/environment';3 import '@fontsource/source-sans-pro';4 import { EmailInputField, TextArea, TextInputField } from '@rodneylab/sveltekit-components';56 let form = $props();78 let name = $state(browser ? (window.sessionStorage.getItem('name') ?? '') : '');9 let email = $state(browser ? (window.sessionStorage.getItem('email') ?? '') : '');10 let message = $state(browser ? (window.sessionStorage.getItem('message') ?? '') : '');1112 function sessionStore(field, value) {13 if (browser) window.sessionStorage.setItem(field, value);14 }1516 function clearForm() {17 if (browser) {18 sessionStorage.removeItem('name');19 sessionStorage.removeItem('email');20 sessionStorage.removeItem('message');21 }22 name = '';23 email = '';24 message = '';25 }2627 if (form?.success) {28 clearForm();29 }30 </script>3132 <main class="container">33 <div class="content">34 <h1>Write a message</h1>35 <form method="POST" class="form">36 <TextInputField37 value={name}38 id="contact-name"39 name="contact-name"40 placeholder="Blake Costa"41 title="Name"42 on:update={(event) => {43 sessionStore('name', event.detail);44 name = event.detail;45 }}46 style="padding-bottom:1.25rem;margin-right:1rem"47 />48 <EmailInputField49 value={email}50 id="contact-email"51 name="contact-email"52 placeholder="blake@example.com"53 title="Email"54 error={form?.error}55 on:update={(event) => {56 sessionStore('email', event.detail);57 email = event.detail;58 }}59 style="padding-bottom:1.25rem;margin-right:1rem"60 />61 <TextArea62 value={message}63 id="contact-message"64 name="contact-message"65 placeholder="Enter your message here"66 title="Message"67 on:update={(event) => {68 sessionStore('message', event.detail);69 message = event.detail;70 }}71 style="padding-bottom:1.25rem;margin-right:1rem"72 />73 <div class="button-container">74 <button type="submit">Send your message</button>75 </div>76 </form>77 </div>78 </main>
src/routes/+page.server.js
— click to expand code.
1 import { validEmail } from '$lib/utilities/form';2 import { error, invalid } from '@sveltejs/kit';34 export const actions = {5 default: async ({ request }) => {6 try {7 const form = await request.formData();8 const name = form.get('contact-name');9 const email = form.get('contact-email');10 const message = form.get('contact-message');1112 const errors = { ...validEmail(email) };1314 if (!errors.email) {15 console.log({ name, email, message });16 return { success: true };17 }1819 return invalid(400, { 'contact-email': email, error: errors.email });20 } catch (err) {21 const message = `Error in /login form: ${err}`;22 console.error(message);23 return error(500, message);24 }25 },26 };
🔗 SvelteKit Session Storage: Links #
- Using Local storage with SvelteKit
- Open full demo code repo on GitHub
- NoScript Security Suite Firefox extension
- SvelteKit Form Actions ,
- Svelte component binding and event dispatcher tutorial
- MDN Session Storage docs
🙏🏽 Feedback #
If you have found this video useful, see links below for further related content on this site. I do hope you learned one new thing from the video. Let me know if there are any ways I can improve on it. I hope you will use the code or starter in your own projects. Be sure to share your work on Twitter, giving me a mention, so I can see what you did. Finally, be sure to let me know ideas for other short videos you would like to see. Read on to find ways to get in touch, further below. If you have found this post useful, even though you can only afford even a tiny contribution, please consider supporting me through Buy me a Coffee.
Finally, feel free to share the post on your social media accounts for all your followers who will find it useful. As well as leaving a comment below, you can get in touch via @askRodney on Twitter and also askRodney on Telegram . Also, see further ways to get in touch with Rodney Lab. I post regularly on SvelteKit as well as Search Engine Optimization among other topics. Also, subscribe to the newsletter to keep up-to-date with our latest projects.