React component fetches image details asynchronously, resulting in TypeError when navigating away

27 Views Asked by At

I have a React component called GridCard that is responsible for displaying an image. The image URL is fetched asynchronously, and sometimes it takes time to generate. To handle this, I have implemented a logic where if the imageDetail state is null, the component tries to fetch the image details again.

However, I'm encountering an issue when the user navigates to another page while the image details are still being fetched. In the console, I see an error message: Error fetching image details TypeError: Cannot read properties of undefined (reading 'data').

I am curious what this is happening

Here is the relevant code snippet:

 const [imageDetail, setImageDetail] = useState(imageURL)

 const getImageDetails = async () => {
    try {
      const { result } = await axios.get(`documents/${id}`, {
        cancelToken: source.token
      })

      // If the obtained thumbViewLink is still null, retry after 1 seconds
      if (result?.data?.thumbViewLink === null) {
        setTimeout(getImageDetails, 1000)
      } else {
        setImageDetail(result?.data?.thumbViewLink)
      }
    } catch (error) {
      console.error("Error fetching image details", error)
    }
  }

  useEffect(() => {
    if (imageDetail === null) {
      getImageDetails()
    }
    // Cleanup function to cancel the ongoing API request when the component unmounts
    return () => {
      source.cancel("Component unmounted")
    }
  }, [imageDetail])

0

There are 0 best solutions below