[한끼밀-오류 해결] non-serializable value 오류 해결하기(feat.Redux-Toolkit, Redux-Persist)

hameee·2023년 5월 24일
1

한끼밀 프로젝트

목록 보기
4/5
post-thumbnail

🔗 한끼밀 링크 http://www.hankkimeal.kro.kr

🌈 Intro

Redux-Persist를 사용하기로 하면서, Redux-Toolkit에 Redux-Persist를 적용하는 방법을 찾아 보았다. Redux-Persist의 Github를 보면서 해봤지만 계속 뜨는 에러가 있었다.

action에 직렬화할 수 없는 값이 감지되었습니다.

직렬화란 데이터 타입을 변환하는 것이다. 즉, 데이터 타입 변환이 불가능한 값이 action에 있다는 것이다.

In computing, serialization is the process of translating a data structure or object state into a format that can be stored or transmitted and reconstructed later.
컴퓨터에서, 직렬화는 데이터 구조 또는 개체 상태를 저장하거나 전송하고 나중에 재구성할 수 있는 형식으로 변환하는 프로세스입니다.
-Wikipedia(https://en.wikipedia.org/wiki/Serialization)

그래서 이게 왜 문제인데?

Redux 공식 문서에서 state나 action에 직렬화할 수 없는 값(Promise, Symbols, Maps/Sets, 함수, 클래스 인스턴스)을 넣지 말라고 되어 있다. Redux-Toolkit은 Redux를 쉽게 사용하기 위한 라이브러리이므로 Redux-Toolkit 역시 마찬가지이다.

직렬화할 수 없는 값을 state 또는 action에 넣지 마십시오.
Promise, Symbols, Maps/Sets, 함수 또는 클래스 인스턴스와 같은 직렬화할 수 없는 값을 Redux store state 또는 디스패치되는 actions에 넣지 마십시오. 이것은 Redux DevTools를 통한 디버깅과 같은 기능이 예상대로 작동하도록 합니다. 또한 UI가 예상대로 업데이트되도록 합니다.
-Redux 공식 문서(https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions)

에러 메세지를 다시 보니 값 중에 함수가 있었다.

그러면 어떻게 해?

Redux-Toolkit 공식 문서에서는 dispatch로 전달하는 모든 action 타입을 무시해야 한다고 나와 있다. serializableCheckignoredActions에 무시할 action 타입을 배열로 지정하면 된다.

If using Redux-Persist, you should specifically ignore all the action types it dispatches.
Redux-Persist를 사용하는 경우 디스패치하는 모든 action 타입을 특별히 무시해야 합니다.
-Redux-Toolkit 공식 문서(https://redux-toolkit.js.org/usage/usage-guide#use-with-redux-persist)

직렬화 가능성을 확인할 때 무시할 action 타입의 배열. 기본값은 [].
-Redux-Toolkit 공식 문서(https://redux-toolkit.js.org/api/serializabilityMiddleware#options)

import { configureStore } from '@reduxjs/toolkit'
import {
  FLUSH,
  REHYDRATE,
  PAUSE,
  PERSIST,
  PURGE,
  REGISTER,
} from 'redux-persist'

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: {
        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],
      },
    }),
})

공식 문서 말고 다른 방법은?

직렬화 가능성 검사를 안 하는 것이다. serializableCheck: false라고 작성하면 직렬화 가능성을 검사하는 serializableCheck 미들웨어 자체가 실행되지 않는다.

Each middleware can be excluded from inclusion in the array by passing false for its corresponding field
각 미들웨어는 해당 필드에 false를 전달하여 배열에 포함되지 않도록 제외할 수 있습니다.
-React-Toolkit 공식 문서(https://v1-2-5--redux-starter-kit-docs.netlify.app/api/getDefaultMiddleware#customizing-the-included-middleware)

import { configureStore } from '@reduxjs/toolkit'

const store = configureStore({
  reducer: persistedReducer,
  middleware: (getDefaultMiddleware) =>
    getDefaultMiddleware({
      serializableCheck: false,
    }),
})

하지만 이 방법은 Redux-Persist와 관계없는 데이터에 대한 직렬화 가능성 검사도 하지 않기 때문에 Redux-Toolkit 공식 문서의 예시대로 하는 것이 더 안전할 것 같다.

0개의 댓글