본문 바로가기

Errors

A non-serializable value was detected in the state, in the path

umc study를 하면서 redux를 쓰는 과정에서 겪었던 오류다. 

 

export const userSlice = createSlice({
  name: "user",
  initialState: {
    id: "",
    pw: "",
    res: {},
  },
  reducers: {
    login: (state, action) => {
      state.id = action.payload.id;
      state.pw = action.payload.pw;
      state.res = action.payload.res;
      window.localStorage.setItem("token", state.res.data.accesstoken);
      window.localStorage.setItem("id", state.id);
    },
    logout: (state) => {
      state.user = null;
      window.localStorage.removeItem("token");
      window.localStorage.removeItem("id");
    },
  },
});

 

리덕스 toolkit의 slice 구현 코드이다.

state에 axios로 받아온 res 객체를 저장하고 이 res 객체 데이터 안에 있는 accesstoken을 갖고오려고 했었다.

보면 state로 객체 형식인 res object를 action.payload로 받아오는 코드를 볼 수 있는데, 이것은 리덕스 원칙에 어긋난다.

 

1. 애플리케이션의 모든 상태(state)는 하나의 저장소(store) 안에 하나의 객체 트리 구조로 저장된다.

2. 상태(state)는 읽기 전용(read-only)이다.

3. 변화는 순수 함수로 작성되어야 한다.

 

계속 콘솔에서 경고창이 뜨길래 구글링 해보니까 redux에서 function, promise 등과 같은 non-serializable type을 저장하면, redux-devtools에서 표시가 안되고, 콘솔에서 경고 메세지를 던진다고 한다.

 

 

export const userSlice = createSlice({
  name: "user",
  initialState: {
    id: "",
    pw: "",
    accesstoken: "",
  },
  reducers: {
    login: (state, action) => {
      state.id = action.payload.id;
      state.pw = action.payload.pw;
      window.localStorage.setItem("token", state.accesstoken);
      window.localStorage.setItem("id", state.id);
    },
    logout: (state) => {
      state.user = null;
      window.localStorage.removeItem("token");
      window.localStorage.removeItem("id");
    },
  },
});

 

 

[Redux] Redux의 3가지 원칙 (velog.io)

 

[Redux] Redux의 3가지 원칙

스토어는 하나! 상태는 읽기 전용! 리듀서는 순수 함수!

velog.io