Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/anber/recoil-context
A distributed context on top of Recoil
https://github.com/anber/recoil-context
Last synced: 25 days ago
JSON representation
A distributed context on top of Recoil
- Host: GitHub
- URL: https://github.com/anber/recoil-context
- Owner: Anber
- License: mit
- Created: 2020-05-26T15:28:20.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2023-01-06T07:03:58.000Z (almost 2 years ago)
- Last Synced: 2024-05-01T19:16:25.831Z (6 months ago)
- Language: TypeScript
- Size: 1.66 MB
- Stars: 2
- Watchers: 4
- Forks: 0
- Open Issues: 14
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# `recoil-context`: a distributed context on top of [Recoil](https://recoiljs.org)
## Installation
```
npm install --save recoil-context recoil
// or
yarn add recoil-context recoil
```## Example
```typescript
// WizardContext.tsimport { createContext } from "recoil-context";
const { RecoilContext, useContextValue, useSetContextValue } = createContext({
paymentMethod: "card" as "card" | "paypal",
step: 1,
});export { useContextValue, useSetContextValue };
export default RecoilContext;
``````tsx
// Wizard.tsimport WizardContext, { useContextValue, useSetContextValue } from "./Wizard";
const Tab = ({ children, id }) => {
const setStep = useSetContextValue("step");
return setStep(id)}>{children};
};const Tabs = () => {
const method = useContextValue("paymentMethod");
const step = useContextValue("step");
return (
1}>Payment details
2}>
{method === "card" ? "Card details" : "PayPal authorization"}
3}>Confirmation
)
};const Panels = () => {
const method = useContextValue("paymentMethod");
const step = useContextValue("step");
if (step === 1) { /* … */ }
if (step === 2 && method === "card") { /* … */ }
if (step === 2 && method === "paypal") { /* … */ }
if (step === 3) { /* … */ }
}const Wizard = () => {
return (
);
}
```## API
`recoil-context` exports only one function:
##### `createContext(defaultValues: TValues): { RecoilContext, useContextValue, useSetContextValue }`.
It accepts an object with default values and creates a strictly typed context and pair of hooks for getting and setting values:
* `RecoilContext` is a container for your state and provides values for hooks. Default values can be fully or partially overridden with `initialValues` prop;
* `useContextValue(name: T): TValues[T]` returns current value from the context;
* `useSetContextValue(name: T): Dispatch>` returns a value setter for specified field.## License
MIT