[내일배움캠프 TIL] 43일차

Jaehyeon Ye·2022년 12월 29일
0

오늘 새로 배운 것

redux createSlice에서 기존에 쓰던 코드는

 extraReducers: {
    [__getPost.pending]: (state) => {
      state.isLoading = true; // 네트워크 요청이 시작되면 로딩상태를 true로 변경
    },

이랬는데 아래와 같이도 쓸 수 있는 걸 알게 되었다.

extraReducers:(builder){
  	builder.addCase(__getPost.pending, (state) => {
      state.isLoading = true;
	},

근데 차이가 뭔지에 대해서는 아직 찾지 못했다. 추후에 찾으면 TIL로 다룰 예정이다.
그리고 더 나아가,

const counterSlice = createSlice({
  name:'counterSlice',
  initialState:{
    value:0,
    status:'Welcome'
  },
  reducers:{
    up:(state, action)=>{
      state.value = state.value + action.payload;
    }
  },
  extraReducers: (builder) => {
    builder.addCase(asyncUpFetch.pending, (state,action)=>{
      state.status = 'Loading';
    })
    builder.addCase(asyncUpFetch.fulfilled, (state,action)=>{
      state.value = action.payload;
      state.status = 'complete';
    })
    builder.addCase(asyncUpFetch.rejected, (state,action)=>{
      state.status = 'fail';
    })
  }
});

pending이나 rejected됐을 때 status 값을

const status = useSelector(state=>{
    return state.counter.status;
  });
  return <div>
      
    ...
    
    <div>{count} | {status}</div>
  </div>

화면에 뿌려줄 수도 있는 걸 알게 됐는데 다음 프로젝트 때 이걸 제일 구현해보고 싶다.

하루를 돌아보며...

다음에 또 Slice, extrareducers를 쓰게 되면 fulfilled 상태일 때뿐만 아니라 pending이나 rejected되는 상태에 대해서도 화면에 표시할 수 있게 구현해봐야될 것 같다.
그리고 메인페이지 진행 상태를 화면에 뿌려주는 jsx 부분의 코드가 중복되는 부분을 중복되지 않도록 바꿔보고 switch case문도 사용해봐야겠다.

profile
FE Developer

0개의 댓글