[Recoil] Use selectorFamily to take arguments in your Recoil selectors
阿新 • • 發佈:2020-09-09
In this lesson, we're going to learn how to create Recoil selectors that accept arguments. These are made possible using theselectorFamily
utility function.
We'll start with an existing application that uses a regularselector
to display a sorted array of Todo items, and then we'll refactor it so that we're able to supply the sort type (ascending
descending
) in the React component itself.
For more information onselectorFamily
, have a look at the official RecoilJS docs:https://recoiljs.org/docs/api-reference/utils/selectorFamily
Similar to 'selector', 'selectorFamily' is more functional approach, allow to pass additional parameters to 'get' & 'set' functions.
import React from "react"; import "./styles.css"; import { atom, selectorFamily, useRecoilValue } from "recoil"; import { DateTime } from "luxon"; const currentTime = DateTime.local(); const sortedTodoList = selectorFamily({ key: "sortedTodoList", get: (sortedType) => ({ get }) => { const todos= get(todoList); return sortedType === "ASC" ? todos.sort((a, b) => a.createdAt - b.createdAt) : todos.sort((a, b) => b.createdAt - a.createdAt); } }); const todoList = atom({ key: "todoList", default: [ { name: "buy milk", createdAt: currentTime }, { name: "write a book", createdAt: currentTime.plus({ days: 1 }) }, { name: "do some exercise", createdAt: currentTime.plus({ days: 2 }) } ] }); export default function App() { const sortOrder = "DESC"; const mySortedTodoList = useRecoilValue(sortedTodoList(sortOrder)); return ( <div className="App"> <h1>Todo List</h1> {mySortedTodoList.map((item, index) => ( <p key={index}> {item.name} - {item.createdAt.toISODate()} </p> ))} </div> ); }