Skip to content

Instantly share code, notes, and snippets.

@Brettm12345
Last active December 18, 2019 08:42
Show Gist options
  • Save Brettm12345/4f2ea077cac02d626659812f579c3e99 to your computer and use it in GitHub Desktop.
Save Brettm12345/4f2ea077cac02d626659812f579c3e99 to your computer and use it in GitHub Desktop.
Safe localStorage with fp-ts for ssr applications
import * as ls from 'fp-ts-local-storage'
import { io } from 'fp-ts/lib/IO'
import { none } from 'fp-ts/lib/Option'
import { fold } from 'fp-ts/lib/boolean'
import { constVoid, flow } from 'fp-ts/lib/function'
import { curry } from 'ramda'
const isBrowser = io.of(typeof localStorage === "undefined");
const foldIo = curry(
flow(
fold,
io.of
)
);
const foldNone = foldIo(io.of(none));
const foldVoid = foldIo(constVoid);
export const removeItem = (key: string) =>
flow(
isBrowser,
foldVoid(ls.removeItem(key))
);
export const setItem = (key: string) => (value: string) =>
flow(
isBrowser,
foldVoid(ls.setItem(key, value))
);
export const getItem = (key: string) =>
flow(
isBrowser,
foldNone(ls.getItem(key))
);
@ar1a
Copy link

ar1a commented Dec 18, 2019

i'd recommend writing a function something like

const equals = a => b => a == b

instead of importing ramda just for that

@ar1a
Copy link

ar1a commented Dec 18, 2019

you're importing IO but i don't see it used anywhere

@ar1a
Copy link

ar1a commented Dec 18, 2019

instead of doing qualified imports for option and localstorage, there are no overlapping imports and you could instead just import setItem, getItem, fold

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment