0

I don't understand why the first code returns a promise Promise {<fulfilled>: Array(1)} but the second code returns my data as I expected.

  useEffect(() => {
    getCatalog().then((responseInEffect) => setAllProducts(responseInEffect.json()))
  }, [])

  async function getCatalog() {
    const response = await fetch(
      `${host}/api/products?${new URLSearchParams({ products: "all" })}`,
      {
        method: "GET",
      }
    )
    return response
  }

From my understanding responseInEffect has the same data as the response returned by getCatalog(). But I'm confused when I move the .json() call to getCatalog().

  useEffect(() => {
    getCatalog().then((responseInEffect) => setAllProducts(responseInEffect))
  }, [])

  async function getCatalog() {
    const response = await fetch(
      `${host}/api/products?${new URLSearchParams({ products: "all" })}`,
      {
        method: "GET",
      }
    )
    return response.json()
  }

This second code will return the data as I expected. But all I did was move the .json() call inside the getCatalog(). Can someone please explain why this is?

engineer-x
  • 2,173
  • 2
  • 12
  • 25
  • 1
    `response.json()` returns a promise, which you don't await in the first case. `getCatalog().then(responseInEffect => responseInEffect.json()).then(products => setAllProducts(products))` And just as a sidenote: Before accessing the data of your response, you should ALWAYS check, if the request was successful or not (ie check `response.ok` or `response.status`) so that you can attach proper error handling. – derpirscher Jan 21 '23 at 08:30

0 Answers0