1

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;

2 Answers 2

1

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>
    </>
  );
Sign up to request clarification or add additional context in comments.

5 Comments

So, your just returning different blocks based on conditions?
yeah conditional rendering. priority is like loading, error, data display.
Thanks, so need to to do anything with the state?
no need, based on your state this render works
you can also add null check like this ->. data?.map updated ans also.
1

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>
</>

);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.