Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/razshare/svelte-context-deeznuts
Set and get typed component contexts
https://github.com/razshare/svelte-context-deeznuts
context jsdoc library svelte typescript
Last synced: about 1 month ago
JSON representation
Set and get typed component contexts
- Host: GitHub
- URL: https://github.com/razshare/svelte-context-deeznuts
- Owner: razshare
- Created: 2023-05-26T21:22:55.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2023-05-27T00:26:29.000Z (over 1 year ago)
- Last Synced: 2024-05-28T13:28:34.098Z (7 months ago)
- Topics: context, jsdoc, library, svelte, typescript
- Language: JavaScript
- Homepage: https://tncrazvan.github.io/svelte-context-deeznuts/
- Size: 558 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
![deeznuts](https://github.com/tncrazvan/svelte-context-deeznuts/blob/main/deeznuts.jpg?raw=true "deeznuts")
# Introduction
Svelte Context Deeznuts is a very advanced 58 line library that solves a problem that's already been solved by the svelte standard library.
## Why?
It is often the case that we need to provide some type hinting for component contexts.
Unfortunately `getContext` does not inherit type hints from `setContext` and there is probably no easy way to fix that in the standard library without adding unnecessary complexity to the context api; and I like my standard libraries to be simple.
Some workarounds include creating separate files to define the typed contexts and importing them separately.
I don't like that, all `component.svelte`'s affairs should remain in the `component.svelte` file.
## When to use
Make sure you actually need to use the context api.
This library automatically converts your value into a `Writable`.
Chances are that if you don't need a `Writable` in your context, you probably don't need the context api itself.
We may agree to disagree.
## How to use
Install with
```sh
npm i -D svelte-context-deeznuts
```Create you parent component and set a context.
```svelte
import { set } from 'svelte-context-deeznuts'
set<false | string>('activeID', false)
```
This will create your context.
Then export the getter from the module context.
```svelte
import { get } from 'svelte-context-deeznuts'
export const getActiveID = get<false | string>('activeID')
import { set } from 'svelte-context-deeznuts'
set<false | string>('activeID', false)
```
Once that's done create your child component.
```svelte
import { getActiveID } from './list.svelte'
const activeID = getActiveID()
const id = crypto.randomUUID()
{#if id === $activeID}
(active)
{/if}
```
And to put things together:
```svelte
import Item from './item.svelte'
import List from './list.svelte'
item 1
item 2
item 3
item 4
item 5
```