Created
November 7, 2020 19:32
-
-
Save iambenkay/6ae1ced56477a1e5ee1e395483d55f2e to your computer and use it in GitHub Desktop.
Recoil.js sample code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { atom } from "recoil"; | |
export const historyState = atom({ | |
key: "historyState", | |
default: [] | |
}); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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")); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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