export const cookieAtom = <A, I>(options: {
name: string
schema: Schema.Schema<A, I>
}) => {
const store = globalThis.cookieStore
const decode = Schema.decodeEither(options.schema)
const getValue = pipe(
Effect.promise(() => store.get(options.name)),
Effect.map(Option.fromNullable),
Effect.map(
Option.match({
onNone: () => Option.none<A>(),
onSome: (value) => Either.getRight(decode(value as I))
})
)
)
return Atom.make(
Effect.fn(function*(get: Atom.Context) {
const handleChange = () => {
store.get(options.name).then((newValue) => {
if (newValue === null) {
get.setSelf(Option.none<A>())
return
}
get.setSelf(Either.getRight(decode(newValue as I)))
})
}
store.addEventListener("change", handleChange)
get.addFinalizer(() => {
store.removeEventListener("change", handleChange)
})
return yield* getValue
})
)
}
export const cookieAtom = <A, I>(options: {
name: string
schema: Schema.Schema<A, I>
}) => {
const store = globalThis.cookieStore
const decode = Schema.decodeEither(options.schema)
const getValue = pipe(
Effect.promise(() => store.get(options.name)),
Effect.map(Option.fromNullable),
Effect.map(
Option.match({
onNone: () => Option.none<A>(),
onSome: (value) => Either.getRight(decode(value as I))
})
)
)
return Atom.make(
Effect.fn(function*(get: Atom.Context) {
const handleChange = () => {
store.get(options.name).then((newValue) => {
if (newValue === null) {
get.setSelf(Option.none<A>())
return
}
get.setSelf(Either.getRight(decode(newValue as I)))
})
}
store.addEventListener("change", handleChange)
get.addFinalizer(() => {
store.removeEventListener("change", handleChange)
})
return yield* getValue
})
)
}