1. 程式人生 > 實用技巧 >[Recoil] Use selectorFamily to take arguments in your Recoil selectors

[Recoil] Use selectorFamily to take arguments in your Recoil selectors

In this lesson, we're going to learn how to create Recoil selectors that accept arguments. These are made possible using theselectorFamilyutility function.

We'll start with an existing application that uses a regularselectorto display a sorted array of Todo items, and then we'll refactor it so that we're able to supply the sort type (ascending

ordescending) 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> ); }