
Security News
Deno 2.2 Improves Dependency Management and Expands Node.js Compatibility
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
react-localstorage-ts
Advanced tools
A small library to wrap browser's localstorage in a functional fashion.
A small layer over the browser's localstorage, fallbacks to an in-memory store localstorage is not supported by the browser.
Built on io-ts
and fp-ts
, react-localstorage-ts
gives you a standard way to access objects stored locally using io-ts
's encoding/decoding abilities.
yarn add react-localstorage-ts fp-ts io-ts monocle-ts newtype-ts
npm install react-localstorage-ts fp-ts io-ts monocle-ts newtype-ts
To use react-localstorage-ts
you have to follow a few simple steps:
First you need to define the list of "storable" items by expanding the StoredItems
interface:
// store.ts
import * as t from "io-ts"
export const ThemeFlavour = t.union([t.literal("light"), t.literal("dark")])
export type ThemeFlavour = t.TypeOf<typeof ThemeFlavour>
declare module "react-localstorage-ts" {
interface StoredItems {
access_token: string
theme: ThemeFlavour
}
}
then you create the hooks to read/write the values you just defined:
// localHooks.ts
import * as t from "io-ts"
import {
makeDefaultedUseLocalItem,
makeUseLocalItem,
} from "react-localstorage-ts"
import {ThemeFlavour} from "./store"
export const useThemeFlavour = makeDefaultedUseLocalItem("theme", ThemeFlavour, () => "light")
export const useAccessToken = makeUseLocalItem("access_token", t.string)
then you use them in your react components:
// App.tsx
import * as React from "react"
import * as E from "fp-ts/Either"
import LightThemeApp from "./components/LightThemeApp"
import DarkThemeApp from "./components/DarkThemeApp"
import { useThemeFlavour } from "./localHooks"
const App: React.FC = () => {
const [theme, setTheme] = useThemeFlavour()
return pipe(
theme,
E.fold(
() => {
console.error('wrong value stored in localStorage!')
},
themeFlavour => {
switch (themeFlavour) {
case "light": {
return <LightThemeApp />
}
case "dark": {
return <DarkThemeApp />
}
}
}
)
)
}
export default App
A new data structure is defined for items stored in localstorage, LocalValue
. When dealing with a value stored in your localstorage there are three possibilities:
The structure of LocalValue represent the optionality/correctness dicotomy by using well known contructs, Option
and Either
:
import * as t from "io-ts"
type LocalValue<V> = O.Option<E.Either<t.Errors, V>>
It also has instances for some of the most common type-classes
and you can use it in the same way you usually use your usual fp-ts
abstractions:
// LoginLayout.tsx
import * as LV from "react-localstorage-ts/LocalValue"
import { useAccessToken } from "./localHooks"
import { goToLoginPage } from "./router"
import App from "./App"
const LoginLayout: React.FC = ({ children }) => {
const [token] = useAccessToken()
React.useEffect(() => {
if (!LV.isValid) {
goToLoginPage()
}
}, [])
return pipe(
token,
LV.fold(() => null, () => null, () => <>{ children }</>),
)
}
// LoginPage.tsx
import * as LV from "react-localstorage-ts/LocalValue"
import { goToHomePage } from "./router"
import { useAccessToken } from "./localHooks"
const LoginPage: React.FC = ({ children }) => {
const [token, setToken] = useAccessToken()
React.useEffect(() => {
if (LV.isValid) {
goToHomePage()
}
}, [])
return (
<Form
onSubmit={() => api.getToken.then(t => setToken(t))}
/>
)
}
N.B. when you use makeDefaultedUseLocalItem
, you loose the optionality of your value, so you are left with an Either
instead of a LocalValue
.
creating a custom codec to use with makeUseLocalItem
can be a really non-trivial task, that's why
we ship the utility codec JSONFromString
that can be used to "ease the pain". Here is an example of how you can use it to define a custom codec:
import * as t from "io-ts"
import * as E from "fp-ts/Either"
import { pipe } from "fp-ts/function"
import { JSONFromString, isoJSON } from "react-localstorage-ts/JSONFromString"
const ShapeCodec = t.type({ s: t.string, d: DateFromISOString })
type ShapeCodec = t.TypeOf<typeof ShapeCodec>
const defaultShape: ShapeCodec = {
s: "foo",
d: new Date(),
}
export const ShapeCodecFromString = new t.Type<ShapeCodec, string>(
"ShapeCodecFromString",
ShapeCodec.is,
(u, c) => {
return pipe(
JSONFromString.validate(u, c),
E.chain((json) => ShapeCodec.validate(json, c)),
)
},
(v) => {
return pipe(v, ShapeCodec.encode, isoJSON.wrap, JSONFromString.encode)
},
)
to commit to this repository there are a few rules:
commit-msg
hook).here you can find an explanation of the release flow.
FAQs
A small library to wrap browser's localstorage in a functional fashion.
The npm package react-localstorage-ts receives a total of 378 weekly downloads. As such, react-localstorage-ts popularity was classified as not popular.
We found that react-localstorage-ts demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 2 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Deno 2.2 enhances Node.js compatibility, improves dependency management, adds OpenTelemetry support, and expands linting and task automation for developers.
Security News
React's CRA deprecation announcement sparked community criticism over framework recommendations, leading to quick updates acknowledging build tools like Vite as valid alternatives.
Security News
Ransomware payment rates hit an all-time low in 2024 as law enforcement crackdowns, stronger defenses, and shifting policies make attacks riskier and less profitable.