Package Exports
- unctx
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (unctx) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
🍦 unctx
Composition-api in Vanilla js
What is it?
Vue.js introduced an amazing pattern called Composition API that allows organizing complex logic by spliting it into reusable functions and grouping in logical order. unctx
allows easily implementing composition api pattern in your javascript libraries without hassle.
Integration
In you awesome library:
yarn add unctx
# or
npm install unctx
import { createContext } from 'unctx'
const ctx = createContext()
export const useAwesome = ctx.use
// ...
ctx.call({ test: 1 }, () => {
// This is similar to vue setup function
// Any function called here, can use `useAwesome` to get { test: 1 }
})
User code:
import { useAwesome } from 'awesome-lib'
// ...
function setup() {
const ctx = useAwesome()
}
Using Namespaces
Composition of functions is possible using temporary context injection. Under the hood a temporary singleton variable is kept (per context)
To avoid issues with multiple instances of library, unctx
provides a safe global namespace to access contexts with (kept in globalThis
)
Important: Please use a verbose name for key to avoid conflict with other js libraries. Using npm package name is recommended.
import { useContext } from 'unctx'
const { use: useAwesome, call } = useContext('awesome-lib')
You can also create your own internal namespace with createNamespace
utility for more advanced usecases.
Typescript
A generic type exists on all utilities to be set for instance/context type:
// Return type of useAwesome is Awesome | null
const { use: useAwesome } = createContext<Awesome>()
Pitfalls
context can be only used before first await:
To avoid leaking context, call
method synchronously sets context and unsets it as soon as possible. Because of this, useAwesome
should happen before first await
call and reused if necessary.
async function setup() {
const awesome = useAwesome()
await someFunction()
// useAwesome() returns null here
}
Context conflict
error:
In your library, you should only keep one call()
running at a time (unless calling with same reference for first argument)
For instance this makes an error:
ctx.call({ test: 1 }, () => {
ctx.call({ test: 2 }, () => {
// Throws error!
})
})
License
MIT. Made with 💖