This article was originally published on Rails Designer
It is pretty common in SaaS apps to store certain user preferences or appearance settings. Things like font-size, theme colors or the open/closed state of an accordion.
(this example from my new SaaS stores the state of the navigation's sections)
You could save those settings to the user, especially if you need to restore those between sessions or different browsers. I got you covered with this article on adding simple preferences for Rails. But if these settings don't need to be persisted, this is a really nice and simple alternative.
It involves a small and reusable JavaScript functions and the browser's localStorage. Let's dive right in.
For this example I am going to store the the theme for a user, either light or dark. When dark, a dark class is added to html-element. This can then be used to target the other element's (like with dark:bg-gray-950 when using Tailwind CSS).
As often with Stimulus, let's write the HTML first. This will guide us what to write next:
<div data-controller="theme"> <!-- You can show/hide these buttons based on the .dark class --> <button data-action="theme#update" data-theme-value-param="dark"> Lights Off </button> <button data-action="theme#update" data-theme-value-param="light"> Lights On </button> </div>
Then the controller:
// app/javascript/controllers/theme_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { update({ params: { value } }) { this.#setClass(value); } // private #setClass(theme) { document.documentElement.classList.toggle("dark", theme === "dark"); } }
While simple on the surface, there are two things to note here: the { params: { value } } part and the two attributes in the toggle method.
First the attributes in the update function. It uses something called destructing. Sounds difficult, but it's not and it is a really cool feature of JavaScript. Let's check it out before going further.
By default the event is passed to the get function that contains the params. You've probably seen this before.
get(event) { log(event.params.value) // => "light" or "dark" }
But if you have no need for anything else in the event object, you can omit it, like so:
get({ params }) { log(params.value) // => "light" or "dark" }
Or when you want to use destructing, you can do this:
get({ params: { value } }) { log(value) // => "light" or "dark" }
Cool, right? Then the toggle("dark", theme === "dark"). The second parameter (theme === "dark") is a boolean force parameter that explicitly sets whether the class should be added (true) or removed (false), rather than just toggling back and forth
? Find this all too hard to wrap your head around? Check out JavaScript for Rails Developers. ?
Okay, great. With the above controller you can toggle between light- and dark mode. That is, if you have your CSS wired up as such, but you notice that once the screen is refreshed, the default screen is back. The chosen theme is not persisted!
For that, let's introduce localStorage! It is a web storage API that lets you store key-value pairs (strings) in the browser.
Let's update the controller to store the chosen value ("dark" or "light").
<div data-controller="theme"> <!-- You can show/hide these buttons based on the .dark class --> <button data-action="theme#update" data-theme-value-param="dark"> Lights Off </button> <button data-action="theme#update" data-theme-value-param="light"> Lights On </button> </div>
Then upon controller connect, read the value:
// app/javascript/controllers/theme_controller.js import { Controller } from "@hotwired/stimulus" export default class extends Controller { update({ params: { value } }) { this.#setClass(value); } // private #setClass(theme) { document.documentElement.classList.toggle("dark", theme === "dark"); } }
That's how easy it is store some settings for a user. Note that these values are stored (unencrypted) in their browser. So if they use another browser, the settings are not there. But it's stored also after they restart the browser (unless they clear it).
Besides setItem and getItem, the localStorage API also removeItem and clear().
The above is the detailed content of Store UI State in localStorage with Stimulus. For more information, please follow other related articles on the PHP Chinese website!

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Dreamweaver Mac version
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools
