1

I'm trying to understand the .then catch that is applied to fetch fetch. Currently I have the following POST request that I know works. When I examine the data variable there is an array of data.

fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions) 
        .then(response => response.json())
        .then(data => setStockData(data));

I want to apply some error handling which ive attempted to do in the following update piece of code below. However once i do this the data variable no longer populates with an array of data like it did in the original piece of code above. Why is this and how do i fix it?

 fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions) 
        .then(response => {
          if(!response.ok){
            if(response.status === 404){
              setError("Stock symbol not found please try again");
            }
            else{
              setError("Please check your connection to the database");
            }
          }
          else {
            return response.json();
          }
        })
        .then(data => setStockData(data));
Jane Doe
  • 187
  • 1
  • 12

2 Answers2

0

Because the return response.json(), which decodes the response into JSON, is within an else.

You can imagine a return undefined there:

fetch(`http://...`, requestOptions)
  .then(response => {
    if (!response.ok) {
      if (response.status === 404) {
        setError("Stock symbol not found please try again");
      } else {
        setError("Please check your connection to the database");
      }
    } else {
      return response.json();
    }
    return undefined;
  })
  .then(data => setStockData(data));

If you do want to always (try to) decode the JSON, despite the response OK state, unwrap that last else.

AKX
  • 152,115
  • 15
  • 115
  • 172
-1

then() methods return you a promise which you can read more about at PROMISE

Coming back to your question you should implement something like below. As then take two callbacks one for success and other for rejection you can utilize them to handle the responses.

  fetch(`http://PRIVATE/stocks/authed/${query}?from=${convertedStart}T00%3A00%3A00.000Z&to=${convertedEnd}T00%3A00%3A00.000Z`, requestOptions)
        .then((successReponse) => {

            //If you have to handle status codes 
            if (successReponse.code == "200") {
                //assuming success value has something called data which you want to set
                setStockData(successResponse.data);
            }
            else if (true /* OTHER CODE HANDLER */) {

            }

        }, (rejected) => {
            //If there was a error you can handle here
        });