[TIL] 비동기 delete

이현동·2023년 2월 20일
0

TIL

목록 보기
35/59

Delete 기능

데이터 베이스에서 Delete 기능은 잘 구현이 되는데,
1. 다시 map으로 뿌려줄 때 오류가 나고 -> map is not a function
원인은 우선 배열이 아닌 다른 값이 들어가서 그런 것 같다.
2. 새로고침을 해주어야만 다시 반영이 된다.
새로고침을 해주어야 반영이 된다는 것은 일단 데이터 베이스 상에서는 삭제가 된 것이고 렌더링 하는 과정에서 문제가 있는 것이라고 생각했다.

그래서 처음에는 미들웨어에서 다시 get메소드를 사용했었다.

...

const initialState = {
  post: [],
  isLoading: false,
  error: null,
};

...

export const __deletePost = createAsyncThunk('deletpost', async (payload: any, thunkAPI) => {
  try {
    await axios.delete(`http://localhost:4000/post/${payload}`);
    const data = await axios.get("http://localhost:4000/post");
    return thunkAPI.rejectWithValue(data.data);
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});

...

builder
  .addCase(__deletePost.pending, (state) => {
  state.isLoading = true;
})
  .addCase(__deletePost.fulfilled, (state) => {
  state.isLoading = false;
  state.post = action.payload;
})
  .addCase(__deletePost.rejected, (state, action) => {
  state.error = true;
  state.error = action.payload;
});

...

하지만 위와 같이 미들웨어에서 처리해주면 안된다..

해결

이전 코드

export const __deletePost = createAsyncThunk('deletpost', async (payload, thunkAPI) => {

try {

	const { data } = await axios.delete(`http://localhost:4000/post/${payload}`);

	console.log('thunk API', thunkAPI.fulfillWithValue(data.data));

	return thunkAPI.fulfillWithValue(data.data);

} catch (error) {

	return thunkAPI.rejectWithValue(error);

}

});

위와 같이 코드를 쓴 이유는
const { data } = await axios.delete(http://localhost:4000/post/${payload}`);`
코드에서 내가 생각했던 것은

  1. 데이터 베이스에서 해당 정보를 삭제
  2. data에 넣어받아서 바로 값을 받아옴
  3. 그 값을 return 해줌
    하지만 delete method는 위와 같이 작성 하면 data.data에 빈 객체가 콘솔에 찍힌다. 그리고 나는 그걸 post list라는 data base에 있는 배열에 넣어줬기 때문에 값(데이터 베이스 값)이 들어있는 배열에서 빈 객체로 다시 들어가기 때문에 map is not a function 오류가 나는 것이다.

아래와 코드로 해결

이후 코드

redux > modules > post.ts

...

export const __deletePost = createAsyncThunk('deletpost', async (payload: any, thunkAPI) => {
  try {
    await axios.delete(`http://localhost:4000/post/${payload}`);
  } catch (error) {
    return thunkAPI.rejectWithValue(error);
  }
});

...

builder
      .addCase(__deletePost.pending, (state) => {
        state.isLoading = true;
      })
      .addCase(__deletePost.fulfilled, (state: any) => {
        state.isLoading = false;
      })
      .addCase(__deletePost.rejected, (state, action: any) => {
        state.error = true;
        state.error = action.payload;
      });

...

components > Cards.tsx

...

const deleteBtnHandler = async (id: number) => {
    await dispatch(__deletePost(id));
    dispatch(__getPost());
  };
  
...
profile
https://hdlee.dev

0개의 댓글