MAIS AMOR POR FAVOR

SvelteKit Session Storage: Cache Form Data

SvelteKit Session Storage

SvelteKit Session Storage: Cache Form Data

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

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/index.svelte
javascript
1<script>
2 import { browser } from '$app/env';
3 import { validEmail } from '$lib/utilities/form';
4 import { EmailInputField, TextArea, TextInputField } from '@rodneylab/sveltekit-components';
5 import '@fontsource/source-sans-pro';
6
7 let name = browser ? window.sessionStorage.getItem('name') ?? '' : '';
8 let email = browser ? window.sessionStorage.getItem('email') ?? '' : '';
9 let message = browser ? window.sessionStorage.getItem('message') ?? '' : '';
10
11 function sessionStore(field, value) {
12 if (browser) {
13 window.sessionStorage.setItem(field, value);
14 }
15 }
16
17 function clearForm() {
18 if (browser) {
19 sessionStorage.removeItem('name');
20 sessionStorage.removeItem('email');
21 sessionStorage.removeItem('message');
22 }
23 name = '';
24 email = '';
25 message = '';
26 }
27
28 function validateInputs() {
29 errors = { ...errors, ...validEmail(email) };
30 }
31
32 function handleSubmit() {
33 validateInputs();
34 console.log({ name, email, message });
35 clearForm();
36 }
37</script>
38
39<main class="container">
40 <div class="content">
41 <h1>Write a message</h1>
42 <form class="form" on:submit|preventDefault={handleSubmit}>
43 <TextInputField
44 value={name}
45 id="contact-name"
46 placeholder="Blake Costa"
47 title="Name"
48 on:update={(event) => {
49 sessionStore('name', event.detail);
50 name = event.detail;
51 }}
52 style="padding-bottom:1.25rem;margin-right:1rem"
53 />
54 <EmailInputField
55 value={email}
56 id="contact-email"
57 placeholder="[email protected]"
58 title="Email"
59 on:update={(event) => {
60 sessionStore('email', event.detail);
61 email = event.detail;
62 }}
63 style="padding-bottom:1.25rem;margin-right:1rem"
64 />
65 <TextArea
66 value={message}
67 id="contact-message"
68 placeholder="Enter your message here"
69 title="Message"
70 on:update={(event) => {
71 sessionStore('message', event.detail);
72 message = event.detail;
73 }}
74 style="padding-bottom:1.25rem;margin-right:1rem"
75 />
76 <div class="button-container">
77 <button type="submit">Send your message</button>
78 </div>
79 </form>
80 </div>
81</main>
82
83<style>
84 :global(html) {
85 font-family: 'Source Sans Pro';
86 background-color: #007fff;
87 color: #fcfcff;
88 accent-color: #291720;
89 }
90
91 :global(h1) {
92 font-size: 1.953rem;
93 }
94
95 :global(input),
96 :global(textarea) {
97 border-style: none;
98 background: #fcfcff;
99 border-radius: 2px;
100 line-height: 1.75;
101 padding: 0 0.5rem;
102 font-size: 1.25rem;
103 }
104
105 form {
106 margin-top: 1.5rem;
107 }
108 .button-container {
109 display: flex;
110 width: 100%;
111 }
112
113 button {
114 cursor: pointer;
115 color: #ffd791;
116 background-color: #291720;
117 border-style: none;
118 border-radius: 1.5rem;
119 font-size: 1.563rem;
120 padding: 0.5rem 1.5rem;
121 margin-top: 1.5rem;
122 margin-left: auto;
123 }
124 @media (prefers-reduced-motion: no-preference) {
125 button {
126 transition: background-color 250ms, color 250ms;
127 }
128 }
129 @media (prefers-reduced-motion: no-preference) {
130 button {
131 transition: background-color 2000ms, color 2000ms;
132 }
133 }
134
135 button:hover {
136 background-color: #686963;
137 color: #fcfcff;
138 }
139
140 .container {
141 display: flex;
142 flex-direction: column;
143 }
144
145 .content {
146 width: 60%;
147 margin: 3rem auto;
148 }
149</style>

πŸ™πŸ½ 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 Optimisation among other topics. Also subscribe to the newsletter to keep up-to-date with our latest projects.