[React JS] Selectors

강서현·2022년 9월 30일
0

Selectors: Recoil에서 제공하는 atom의 output을 편집할 수 있도록 한다.

배열

export enum Categories {
  "TO_DO" = "TO_DO",
  "DOING" = "DOING",
  "DONE" = "DONE",
}
//category가 세 가지 상태 중 하나로 제한됨을 알린다.
//category: "a" | "b" | "c"; 형태도 가능

export interface IToDo {
  text: string;
  id: number;
  category: Categories;
}

export const toDoState = atom<IToDo[]>({
  key: "toDo",
  default: [],
});

toDoState는 Itodo의 배열. Itodo는 id, text, 그리고 enum인 Categories를 가진다.
따라서 toDoState 안의 IToDo들은 TO_DO, DOING, DONE 세 가지 상태 중 하나를 가진다.

1: 과제 제출 TO_DO
2: 강의 듣기 DOING
3: 메일 작성 TO_DO
4: 청소하기 DONE

현재 toDoState의 output이다. 이런 식으로 섞여있는 상태.
TO_DO, DOING, DONE에 해당하는 항목을 따로따로 출력하고자 할 때,
세 가지 atom을 작성하지 않고도 output을 분리할 수 있다.

Selectors

import { atom, selector } from "recoil";

toDoSelector를 작성할 것이다.

export const toDoSelector = selector({
  key: "toDoSelector",
  
    return {};
    
  },
});

우선 categoryState라는 atom을 따로 작성한다.

export const categoryState = atom<Categories>({
  key: "category",
  default: Categories.TO_DO,
});

현재 창의 Categories 값을 반환하기 위한 것이다.
(TO_DO 출력창->"TO_DO" 전달)

Selector는 다른 atom을 가져와서 output을 변화시키는데, 여기서는 toDoState와 categoryState를 가져온다. 가져올 때는 get을 사용한다.

  get: ({ get }) => {
    const toDos = get(toDoState);
    const category = get(categoryState);

그리고 filter를 사용해 카테고리가 categoryState에 해당하는 것만 남긴다.

return toDos.filter((toDo) => toDo.category === category);

전부 합치면 이런 형태가 된다.

//다른 atom을 가져와 output을 변화시킨다. 
export const toDoSelector = selector({
  key: "toDoSelector",
//   selector에겐 get이 필요하다. 내부로 atom 가져옴.
  get: ({ get }) => {
    // toDoState 가져오기
    const toDos = get(toDoState);
    const category = get(categoryState);
    // filter를 사용해 조건을 만족하는 항목만 남긴다.
    return toDos.filter((toDo) => toDo.category === category);
  },
});

0개의 댓글