[DAY55] TIL

1nxeo·2023년 4월 2일

항해99

목록 보기
53/63
post-thumbnail

찜 기능 구현할때 숫자가 바로 안올라감. 근데 서버에서는 좋아요 수가 올라감.

리덕스로 상태관리를 해줘서 바로 올리게 해줌.

// 게시물 찜 함수
  export const __likeDetail = createAsyncThunk('postDetail', async (payload, thunkAPI) => {
    try {
      const {pdId} = payload
      await api.post(`${process.env.REACT_APP_SERVER_URL}/products/${pdId}/dibs`);

      return thunkAPI.fulfillWithValue(payload)
    } catch (error) {
      alert("로그인 후 이용해주세요 !")
      return thunkAPI.rejectWithValue(error)
    }
  })

extraReducer 부분

// 게시물 찜 Reducer -------------------------------
        [__likeDetail.pending]: (state, action) => {
          state.isLoading = true
          state.error = false
        },
        [__likeDetail.fulfilled]: (state, action) => {
          // dibs 여부에 따라 + , - 해주기
          const countNum = state.posts.dibs ? state.posts.dibsNum-1:state.posts.dibsNum+1
          state.isLoading = false
          state.error = false
          state.posts = {...state.posts, dibs:!state.posts.dibs, dibsNum:countNum}
        },
        [__likeDetail.rejected]: (state, action) => {
          state.isLoading = false
          state.error = action.payload
        },
profile
항상 피곤한 인서의 개발블로그

0개의 댓글