[TIL] Redux-saga 함수 select, call

햄스터아저씨·2021년 7월 17일
0

Redux-saga 사용법2

1. Redux에 들어있는 정보 읽기

roomlis 가 slice 이름이고 currentRoomId 가 들어있을 때,
아래와 같이 getCurrentRoomId 함수형태로 선언하면
select()함수를 통해 사용할 수 있다.

const getCurrentRoomId = (state) => state.roomlist.currentRoomId;

function* postChanged(action) {
  const { updateMeta, updateRoomLatestContents } = actions;
  try {
    const roomid = yield select(getCurrentRoomId);
    ...
  } catch (err) {
    ...
  }
}

2. saga에서 외부함수 호출하기

함수 FileSystem.readAsStringAsync(chatsDir + action.payload) 를 예시로 든다.
이를 saga에서 호출할 시, call() 함수를 사용해 함수와 파라미터를 분리해 호출한다.

import * as FileSystem from "expo-file-system";
import { chatsDir, ensureChatDirExists } from "@components/File/ensure";

function* openRooms(action) {
  const { updateRoomChatData } = actions;
  try {
    yield call(ensureChatDirExists);
    const stringData = yield call(
      FileSystem.readAsStringAsync,
      chatsDir + action.payload
    );
    ...
  } catch (err) {
    ...
  }
}

사실 여기에서는 call() 필요없이 바로 호출해도 동일한 결과가 나온다.
예시코드 링크

profile
서버도 하고 웹도 하고 시스템이나 인프라나 네트워크나 그냥 다 함.

0개의 댓글