Skip to content

Instantly share code, notes, and snippets.

@iambenkay
Created November 7, 2020 19:32
Show Gist options
  • Save iambenkay/6ae1ced56477a1e5ee1e395483d55f2e to your computer and use it in GitHub Desktop.
Save iambenkay/6ae1ced56477a1e5ee1e395483d55f2e to your computer and use it in GitHub Desktop.
Recoil.js sample code
import { atom } from "recoil";
export const historyState = atom({
key: "historyState",
default: []
});
import { useRecoilValue, useSetRecoilState, useRecoilState } from "recoil";
import { historyState } from "./atoms";
import { countState, countByRecordState } from "./selectors";
/* In a component you can use these hooks to access the data in your atoms and selectors */
// to access a getter for the historyState atom
const historyValue = useRecoilValue(historyState);
// to access a setter for the historyState atom instead
const historySetter = useSetRecoilState(historyState);
// to access a getter and setter for the historyState atom
const [history, setHistory] = useRecoilState(historyState);
// You subscribe to selectors the same way you subscribe to atoms
const count = useRecoilValue(countState);
const countByRecord = useRecoilValue(countByRecordState("item"));
import { selector, selectorFamily } from "recoil";
import { historyState } from "./atoms";
export const countState = selector({
key: "countState",
get({ get }) {
const history = get(historyState);
return history.length;
}
});
export const countByRecordState = selectorFamily({
key: "countByRecordState",
get: record => ({ get }) => {
const history = get(historyState);
return history.filter(item => item === record).length;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment