|
| 1 | +<p> |
| 2 | + <img width="100%" src="https://assets.solidjs.com/banner?type=Primitives&background=tiles&project=cookies" alt="Solid Primitives cookies"> |
| 3 | +</p> |
| 4 | + |
| 5 | +# @solid-primitives/cookies |
| 6 | + |
| 7 | +[](https://turborepo.org/) |
| 8 | +[](https://bundlephobia.com/package/@solid-primitives/cookies) |
| 9 | +[](https://www.npmjs.com/package/@solid-primitives/cookies) |
| 10 | +[](https://github.com/solidjs-community/solid-primitives#contribution-process) |
| 11 | + |
| 12 | +A set of primitives for handling cookies in solid |
| 13 | + |
| 14 | +- [`createServerCookie`](#createservercookie) - Provides a getter and setter for a reactive cookie, which works isomorphically. |
| 15 | +- [`createUserTheme`](#createusertheme) - Creates a Server Cookie providing a type safe way to store a theme and access it on the server or client. |
| 16 | + |
| 17 | +## Installation |
| 18 | + |
| 19 | +```bash |
| 20 | +npm install @solid-primitives/cookies |
| 21 | +# or |
| 22 | +yarn add @solid-primitives/cookies |
| 23 | +# or |
| 24 | +pnpm add @solid-primitives/cookies |
| 25 | +``` |
| 26 | + |
| 27 | +## How to use it |
| 28 | + |
| 29 | +## `createServerCookie` |
| 30 | + |
| 31 | +A primitive for creating a cookie that can be accessed isomorphically on the client, or the server. |
| 32 | + |
| 33 | +```ts |
| 34 | +const [cookie, setCookie] = createServerCookie("cookieName"); |
| 35 | + |
| 36 | +cookie(); // => string | undefined |
| 37 | +``` |
| 38 | + |
| 39 | +### Custom serialization |
| 40 | + |
| 41 | +Custom cookie serializers and deserializers can also be implemented |
| 42 | + |
| 43 | +```ts |
| 44 | +const [serverCookie, setServerCookie] = createServerCookie("coolCookie", { |
| 45 | + deserialize: str => (str ? str.split(" ") : []), // Deserializes cookie into a string[] |
| 46 | + serialize: val => (val ? val.join(" ") : ""), // serializes the value back into a string |
| 47 | +}); |
| 48 | + |
| 49 | +serverCookie(); // => string[] |
| 50 | +``` |
| 51 | + |
| 52 | +## `createUserTheme` |
| 53 | + |
| 54 | +Composes `createServerCookie` to provide a type safe way to store a theme and access it on the server or client. |
| 55 | + |
| 56 | +```ts |
| 57 | +const [theme, setTheme] = createUserTheme("cookieName"); |
| 58 | + |
| 59 | +theme(); // => "light" | "dark" | undefined |
| 60 | + |
| 61 | +// with default value |
| 62 | +const [theme, setTheme] = createUserTheme("cookieName", { |
| 63 | + defaultValue: "light", |
| 64 | +}); |
| 65 | + |
| 66 | +theme(); // => "light" | "dark" |
| 67 | +``` |
| 68 | + |
| 69 | +## Examples |
| 70 | + |
| 71 | +Coming soon |
| 72 | + |
| 73 | +## Demo |
| 74 | + |
| 75 | +You can view a demo of this primitive here: <https://codesandbox.io/p/sandbox/amazing-easley-wqk38i?file=%2Fsrc%2Fcookies_primitive%2Findex.ts%3A36%2C20> |
| 76 | + |
| 77 | +## Changelog |
| 78 | + |
| 79 | +See [CHANGELOG.md](./CHANGELOG.md) |
0 commit comments