Opens an external site in a new window
Mental Health Awareness Month
“Community”
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links
  • Profile
RODNEY LAB
  • Home
  • Plus +
  • Newsletter
  • Links

SvelteKit Session Storage: Cache Form Data # SvelteKit Session Storage: Cache Form Data #

blurry low resolution placeholder image SvelteKit Session Storage
  1. Home Rodney Lab Home
  2. Blog Posts Rodney Lab Blog Posts
  3. SvelteKit SvelteKit Blog Posts
<PREVIOUS POST
NEXT POST >
LATEST POST >>

SvelteKit Session Storage: Cache Form Data #

Updated 4 months ago
4 minute read
Gunning Fog Index: 5.2
3 comments
Content by Rodney
blurry low resolution placeholder image Author Image: Rodney from Rodney Lab
SHARE:

🖥 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 📼

SvelteKit Session Storage

🗳 Poll #

How familiar are you with binding form values and event dispatching in SvelteKit?
Voting reveals latest results.

🖥 SvelteKit Session Storage: Code #

src/routes/+page.svelte — click to expand code.
src/routes/+page.svelte
svelte
    
1 <script>
2 import { browser } from '$app/environment';
3 import '@fontsource/source-sans-pro';
4 import { EmailInputField, TextArea, TextInputField } from '@rodneylab/sveltekit-components';
5
6 let form = $props();
7
8 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') ?? '') : '');
11
12 function sessionStore(field, value) {
13 if (browser) window.sessionStorage.setItem(field, value);
14 }
15
16 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 }
26
27 if (form?.success) {
28 clearForm();
29 }
30 </script>
31
32 <main class="container">
33 <div class="content">
34 <h1>Write a message</h1>
35 <form method="POST" class="form">
36 <TextInputField
37 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 <EmailInputField
49 value={email}
50 id="contact-email"
51 name="contact-email"
52 placeholder="[email protected]"
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 <TextArea
62 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.
src/routes/+page.server.js
javascript
    
1 import { validEmail } from '$lib/utilities/form';
2 import { error, invalid } from '@sveltejs/kit';
3
4 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');
11
12 const errors = { ...validEmail(email) };
13
14 if (!errors.email) {
15 console.log({ name, email, message });
16 return { success: true };
17 }
18
19 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.

Thanks for reading this post. I hope you found it valuable. Please get in touch with your feedback and suggestions for posts you would like to see. Read more about me …

blurry low resolution placeholder image Rodney from Rodney Lab
TAGS:
SVELTEKIT

Related Posts

blurry low resolution placeholder image SvelteKit Forms: Grammar Check App 📝

SvelteKit Forms: Grammar Check App 📝

sveltekit
<PREVIOUS POST
NEXT POST >
LATEST POST >>

Leave a comment …

Your information will be handled in line with our Privacy Policy .

Comments

  • Alain BUFERNE

    Good topic and explaination but for the video: speak too fast and more is music, music is ok when there is nobody talking but why adding disturbing sound to a technical teaching speech... I don't understand

    4 years ago
    • Rodney

      Hi Alain, just updated the video, and speak a bit slower now! Hope it's better, kept the music but it's at a lower level. You might prefer the tutorials at Rodney Lab Plus SvelteKit tutorials which have no background music.
      3 years ago
  • Rodney

    Hi Alain, thanks for taking the time to leave a comment and sharing your feedback. I do agree the music is a little too loud on this video and also at the start I do speak quite quickly. I do hope despite this you are still able to learn something. I have very limited time to create this free content, but will rerecord this video when I am able to find the time. Bearing that in mind, do let me know if there is some extra detail it might be helpful to include in the new edition. Kindest regards, Rodney.

    4 years ago

Ask for more

1 Nov 2022 — Astro Server-Side Rendering: Edge Search Site
3 Oct 2022 — Svelte eCommerce Site: SvelteKit Snipcart Storefront
1 Sept 2022 — Get Started with SvelteKit Headless WordPress

Copyright © 2020 – 2025 Rodney Johnson. All Rights Reserved. Please read important copyright and intellectual property information.

  • Home
  • Profile
  • Plus +
  • Newsletter
  • Contact
  • Links
  • Terms of Use
  • Privacy Policy
We use cookies  to enhance visitors’ experience. Please click the “Options” button to make your choice.  Learn more here.