TIL

최근 본 상품 구현

nana-log 2023. 8. 11. 10:05

처음 작성한 코드

  const { data } = useQuery(FETCH_USEDITEM, {
    variables: { useditemId: router.query.useditemId },
  })
  
  useEffect(() => {
    const productsRecentlyViewed = JSON.parse(
      localStorage.getItem("productsRecentlyViewed") ?? "[]"
    )

    productsRecentlyViewed.push(JSON.stringify(data))

    console.log(productsRecentlyViewed)

    localStorage.setItem(
      "ProductsRecentlyViewed",
      JSON.stringify(productsRecentlyViewed)
    )
  }, [])

 

https://stackoverflow.com/questions/60008587/usequery-data-undefined-when-calling-useeffect-hook

 

useQuery data undefined when calling useEffect hook?

I'm a bit baffled here. According to this SO question and also this question, I should be able to call the useEffect hook after calling the useQuery hook to populate state, which I am doing via

stackoverflow.com

여기 답변을 보고 코드를 수정했다.

useEffect는 마운트 시 실행되며 데이터가 변경될 때마다 API 호출이 완료된 경우에만 데이터가 변경됩니다. 초기 useEffect 호출은 useQuery가 서버로부터 응답을 받기 전에 발생하므로 내부 useEffect 데이터가 설정된다고 가정할 수 없습니다.
useEffect(() => {
  if (data) {
    dispatch({
      type: types.INIT,
      payload: {
        foo: data.foo,
        bar: data.bar,
        baz: data.baz
      }
    });
  }
}, [data]);

 

수정한 코드

  const { data } = useQuery(FETCH_USEDITEM, {
    variables: { useditemId: router.query.useditemId },
  })

  useEffect(() => {
    const productsRecentlyViewed = JSON.parse(
      localStorage.getItem("productsRecentlyViewed") ?? "[]"
    )

    if (data !== undefined) {
      productsRecentlyViewed.push(JSON.stringify(data))
    }

    console.log(productsRecentlyViewed)

    localStorage.setItem(
      "ProductsRecentlyViewed",
      JSON.stringify(productsRecentlyViewed)
    )
  }, [data])