[TIL] 내배캠4기-React-58일차

hare·2022년 12월 28일
0

내배캠-TIL

목록 보기
42/75

Patch 에러

PATCH url/”id값” net::ERR_CONNECTION_REFUSED

🚨 상세페이지 보드 편집 초안 중.. patch 에러가 발생하며 변경한 내용이 제대로 db.json에 반영되지 않았다.

  • 오류 해결 전 코드
    const patchBoardThunk = createAsyncThunk(
      "board/patchBoard",
      async(payload, thunkAPI)=>{
        try {
          const data =  await axios.patch(`${BASE_URL}/${payload.id}`, payload );
          return thunkAPI.fulfillWithValue(data.data);
        } catch (error) {
          return thunkAPI.rejectWithValue(error.message);
        }
      }
    )
    .
    .
    .
    builder.addCase(patchBoardThunk.fulfilled, (state, action) => {
          const { id, content } = action.payload;
          state.isLoading = false;
        state.boards = state.boards.map((item) => {
          if (item.id === id) {
            return { ...item, content: content };
          } else {
            return item;
          }
        });
        });
    dispatch을 부른 컴포넌트에서 id, content 만 인자로 넘겨줬는데, 이러면 정상적으로 동작하지 않는다고 한다. 취사 선택해서 예전에 했던 방식으로 content 값만 변경하면 될 줄 알았는데.. 📌 patch할 때, thunk에 해당 객체가 구성하고 있는 모든 key와 value를 넘겨주자
  • 해결 후 코드
    //boardSlice.js
    const patchBoardThunk = createAsyncThunk(
      "board/patchBoard",
      async (payload, thunkAPI) => {
        try {
          await axios.patch(`${BASE_URL}/${payload.id}`, payload);
          const data = await axios.get(BASE_URL);
          return thunkAPI.fulfillWithValue(data.data);
        } catch (error) {
          return thunkAPI.rejectWithValue(error.message);
        }
      }
    );
    .
    .
    .
    builder.addCase(patchBoardThunk.fulfilled, (state, action) => {
          state.isLoading = false;
          state.boards = action.payload;
        });
    builder 안에 불필요했던 map 메서드도 지워준다. thunk 함수 안, data 에 await axios.get(BASE_URL) 을 할당 → 계속해서 바뀐 값을 추적할 수 있도록 한다는 의미
    //Detail.jsx
    const newBoard = {
          id: params,
          content: content,
          name: board.name,
          pw: board.pw,
          title: board.title,
        };
    
        dispatch(patchBoardThunk(newBoard));
    변경하고자 하는 content만 제외하고 전부 기존 값 그대로 주었다.
profile
해뜰날

0개의 댓글