0

Take the following code in my React component:

  const getPhotos = async (page?: number) => { 
    setLoading(true);
    try {
      const data = await endpoints.getCuratedPhotos(page)
      if (!data) {
        setError('No Photos found')
        setLoading(false);
      } else {
        setPhotos(data);
        setSearchQuery(null)
        setLoading(false);
      }

    } catch (e) {
      console.log('error something went wrong', e);
      setError(`error something went wrong, ${e}`)
      setLoading(false);
    }
  }

  useEffect(() => {
    getPhotos();
  }, [])

Is it necessary or even good practice to have an if statement checking for !data in the try block? Is there scenario where this would be triggered other than a developer changing the URL in the endpoint? Is it sufficient to just have my catch block catch all the errors? Thank you in advance.

London804
  • 1,072
  • 1
  • 22
  • 47
  • Please show us the implementation of `endpoints.getCuratedPhotos`. We can't answer the question otherwise. – Bergi Mar 16 '23 at 18:02
  • @London804 you should want to avoid all the micromanagement of loading and error handling every time you make an async request. it will help separate your api methods and components, making it easier to write both. does [this Q&A](https://stackoverflow.com/a/75594967/633183) help you? – Mulan Mar 17 '23 at 02:43

1 Answers1

2

It’s actually a good practice to verify your data:

  1. It help’s you render only valid data and avoid broken UI.
  2. It help’s you showing consistent error message to your user

In addition, there is a way to refactor your function a little bit using finally which is called with or without error:

const getPhotos = async (page?: number) => { 
  setLoading(true);

  try {
    const data = await endpoints.getCuratedPhotos(page)
    if (!data) {
      setError('No Photos found')
    } else {
      setPhotos(data);
      setSearchQuery(null)
    }

  } catch (e) {
    setError(`error something went wrong, ${e}`)
  } finally {
    setLoading(false);
  }
}
devpolo
  • 2,487
  • 3
  • 12
  • 28