Sole
Sole

Reputation: 3340

Correct way to handle errors and display message in React using Hooks

What would be the best way to handle errors and display them in a React App using Hooks, at the moment if I try to break the app by mistyping the URL it shows the error but still the data sometimes also, however if I update the state to an empty array in the catch block setData([]);, then it works fine, I just wanted to check and see if this is the ideal way or is there another way?

App.js

import React, {useEffect} from 'react';
import './App.css';
import axios from 'axios';

const App = () => {

  interface DataHolder {
    userId: string;
    id: string;
    title: string;
    body: string;
  }

  const [data, setData] = React.useState<DataHolder[]>([]);
  const [isLoading, setIsLoading] = React.useState<Boolean>(false);
  const [hasError, setHasError] = React.useState<Boolean>(false)

  useEffect( () => {
    const fetchData = async (): Promise<any> => {
    setIsLoading(true);
    setHasError(false);
    try {
        const result = await axios('https://jsonplaceholder.typicode.com/posts');
        setData(result.data);
    } catch (err) {
        setHasError(true);
        setData([]);
        console.log(err);
    }
    setIsLoading(false);
  }
  fetchData()
    return () => {
        console.log('cleaned');
    }
}, [setData]);

  return (
    <>
    {hasError && <p >Something went wrong. problem with the data feed.</p>}
    {isLoading ? (
    <p >Loading ...</p>
  ) : (
    <ul>
      {data.map(item => (
        <li key={item.id} >
          <p>{item.title}</p>
        </li>
      ))}
    </ul>
  )}
    </>
  );
}

export default App;

Upvotes: 1

Views: 181

Answers (2)

Amruth
Amruth

Reputation: 5912

Conditional rendering should help when you are dealing with hooks.

  1. Loading
  2. Error
  3. Data display part

You can order like this.

  if (isLoading) {
    return <p>Loading ...</p>;
  }
  if (hasError) {
    return <p>Something went wrong. problem with the data feed.</p>;
  }
  return (
    <>
      <ul>
        {data?.map((item) => (
          <li key={item.id}>
            <p>{item.title}</p>
          </li>
        ))}
      </ul>
    </>
  );

Upvotes: 1

sachin sachu
sachin sachu

Reputation: 137

You can also give a condition like this, checking the length of the data

return (
<>
  <ul>
    {data.length > 0 ? data.map((item) => (
      <li key={item.id}>
        <p>{item.title}</p>
      </li>
    )) : null}
  </ul>
</>

);

Upvotes: 1

Related Questions