Ecosyste.ms: Awesome

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

Awesome Lists | Featured Topics | Projects

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

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.ts

import { createContext } from "recoil-context";

const { RecoilContext, useContextValue, useSetContextValue } = createContext({
paymentMethod: "card" as "card" | "paypal",
step: 1,
});

export { useContextValue, useSetContextValue };

export default RecoilContext;
```

```tsx
// Wizard.ts

import 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