React - API conditional rendering when data has issues

0 votes
123 views
added Mar 19 in React by lcjr First Warrant Officer (11,970 points)

In this example:

  • if (!response.ok) check to throw an error if the response status is not ok (i.e., not in the 200-299 range).
  • In the catch block, we set the searchText state to display the error message to the user.
  • Finally, we set isLoading to false in the finally block to indicate that the loading process is complete.
const fetchData = async () => {
  try {
    const data = JSON.stringify({
      "input": {
        "message": inputValue
      }
    });

    const response = await fetch(YOUR_API, {
      method: 'POST',
      // headers: {
      //   'Content-Type': 'application/json',
      // },
      body: data,
    });

    if (!response.ok) {
      throw new Error('Network response was not ok');
    }

    const responseData = await response.json();
    setResponseData(responseData);
    // Update search history with the new input value and response
    setSearchHistory((prevSearchHistory) => [
      ...prevSearchHistory,
      { question: inputValue, answer: responseData.output.response.content },
    ]);
  } catch (error) {
    console.error('Error:', error);
    // Display error message to the user
    setSearchText('Your search is unavailable at the moment');
  } finally {
    setIsLoading(false);
  }
};

in JSX

<div className="buddyResultContainer">
  {searchText ? (
    <div className="search-error">{searchText}</div>
  ) : (
    searchHistory.map((item, index) => (
      <div 
        key={index} 
        className="buddy_qa_item"
        ref={index === searchHistory.length - 1 ? setLastItemRef : null}
      >
        {/* Your existing code to display search history */}
      </div>
    ))
  )}
</div>

 

lazacode.org - Malaysia's programming knowledge sharing platform, where everyone can share their finding as reference to others.
...