Comparing version 0.0.3 to 0.0.4
interface UseContext<T> { | ||
use: () => T | null; | ||
call: <R>(ctx: T, cb: () => R) => R; | ||
set: (instance?: T, replace?: Boolean) => void; | ||
unset: () => void; | ||
call: <R>(instance: T, cb: () => R) => R; | ||
} | ||
@@ -5,0 +7,0 @@ declare function createContext<T = any>(): UseContext<T>; |
@@ -7,12 +7,29 @@ 'use strict'; | ||
let currentInstance = null; | ||
const checkConflict = (instance) => { | ||
if (currentInstance && currentInstance !== instance) { | ||
throw new Error("Context conflict"); | ||
} | ||
}; | ||
return { | ||
use: () => currentInstance, | ||
call: (instance, cb) => { | ||
if (currentInstance && currentInstance !== instance) { | ||
throw new Error("Context conflict"); | ||
set: (instance, replace) => { | ||
if (!replace) { | ||
checkConflict(instance); | ||
} | ||
currentInstance = instance; | ||
const res = cb(); | ||
}, | ||
unset: () => { | ||
currentInstance = null; | ||
return res; | ||
}, | ||
call: (instance, cb) => { | ||
checkConflict(instance); | ||
currentInstance = instance; | ||
try { | ||
const res = cb(); | ||
currentInstance = null; | ||
return res; | ||
} catch (err) { | ||
currentInstance = null; | ||
throw err; | ||
} | ||
} | ||
@@ -19,0 +36,0 @@ }; |
{ | ||
"name": "unctx", | ||
"version": "0.0.3", | ||
"version": "0.0.4", | ||
"description": "Composition-api in Vanilla js", | ||
@@ -5,0 +5,0 @@ "repository": "unjs/unctx", |
@@ -17,3 +17,3 @@ # 🍦 unctx | ||
In you **awesome** library: | ||
In your **awesome** library: | ||
@@ -66,2 +66,20 @@ ```bash | ||
## Singleton Pattern | ||
If you are sure it is safe to use a shared instance (not depending to request), you can also use `ctx.set` and `ctx.unset` for a [singleton pattern](https://en.wikipedia.org/wiki/Singleton_pattern). | ||
**Note:** You cannot combine `set` with `call`. Always use `unset` before replacing instance otherwise you will get `Context conflict` error. | ||
```js | ||
import { createContext } from 'unctx' | ||
const ctx = createContext() | ||
ctx.set(new Awesome()) | ||
// Replacing instance without unset | ||
// ctx.set(new Awesome(), true) | ||
export const useAwesome = ctx.use | ||
``` | ||
## Typescript | ||
@@ -68,0 +86,0 @@ |
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
9949
121
143
6