How to create a reactive localstorage?
Hi, I need to create a reactive localstorage for localization on my site but I don't know how to do it,
here is my attempt to make one:
but it doesn't work because when the page reloads, the value reverts to the original value
25 Replies
the most straightforward way is to just write to local storage when you write to a signal/store
and then read from local storage to get the initial value during creating
This option is not suitable because I have a lot of components and only in the component where the language is changed it will work.
This signal would usually be global, so it should work in other components as well
So there is no way without contexts, like you can't just track changes to locastorage?
There is no built in way, but it should be really simple to do. Maybe you want to check out https://primitives.solidjs.community/package/storage#createLocalStorage
Solid Primitives
A library of high-quality primitives that extend SolidJS reactivity
you can
there is some event listener for that
but since you are causing the change
you know when it happens
also you a global signal doesn’t have to mean context
just create it somewhere and import in all files needed
I installed it, but it's not there.
createStorage
yeah, seems like you would use
makePersisted
, createLocalStorage
does not exist anymore? or is just deprecatedthey don't exist
https://playground.solidjs.com/anonymous/89fd1a4c-8063-45ee-a99c-4da476a9441c
makePersisted
definitely existsSolid Playground
Quickly discover what the solid compiler will generate from your JSX template
how did you install it?
using npm
npm install @solid-primitives/storage
Make sure you have
"@solid-primitives/storage": "2.1.4"
in your package.json
dependencies, then npm install:can't help more than that I'm afraid
nothing
can you try directly importing like I showed?
ok
wow, it's working.
yeah ts can get wonky
he was able to find this function
But an important thing: you will still want to
makePersisted
once in your application and not in each component.
then you can just import the getter and setter you get from makePersisted
into other components
need to get back to work! See you later 👋okay
bye
🤑
Thanks a lot
🤩🤩🤩🤩😋😋😋😋🤑🤑
Heres a hook that subscribes for events like store event that fires when theres a change in the value stored
Then just use it