Ecosyste.ms: Awesome

An open API service indexing awesome lists of open source software.

Awesome Lists | Featured Topics | Projects

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

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()

  • ($activeID = id)}>



    {#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

    ```