Skip to content

How to define time out to API petition using axios reactjs

I am trying to set timeout to API petition in case i get some error using get, then Loader keeps running for at least 3 seconds to finally show a text sayd “no data or API connection/petition failed”.

I have Dashboard.jsx that works perfectly if theres not error for url, server API fallen, etc. To simulate an error i just changed url and I turned off the server but i get TypeError: paciente.map is not a function and Loader dies instantly.

I tried setting timeout: 3000 in axios but get anything

export const Dashboard = (props) => {
  const [paciente, setPaciente] = useState([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState(null);
  const [errormsg, setErrormsg] = useState("");

  const navigate = useNavigate();
  let url = `${Apiurl}pacientes?page=1`;
  useEffect(() => {
    setLoading(true);
    axios
      .get(url)
      .then((response) => {
        if (!response.err) {
          setPaciente(response.data);
          setError(null);
        } else {
          setPaciente([]);
          setError(response);
        }
        setLoading(false);
      })
      .catch((error) => {
        setError(error);
        setErrormsg("No data");
        setLoading(false);
      });
  }, []);
  const handleClick = (id) => {
    navigate(`/edit/${id}`);
  };
  return (
    <>
      <Header />
      {loading && (
        <div className="loader-container">
          <Loader />
        </div>
      )}
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {!error ? (
              paciente.map((data, i) => {
                return (
                  <tr key={i} onClick={() => handleClick(data.PacienteId)}>
                    <td>{data.PacienteId}</td>
                    <td>{data.DNI}</td>
                    <td>{data.Nombre}</td>
                    <td>{data.Telefono}</td>
                    <td>{data.Correo}</td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan="5">{errormsg}</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );
};

Answer

const navigate = useNavigate();
  let url = `${Apiurl}pacientes?page=1`;
  useEffect(() => {
    setLoading(true);
    axios
      .get(url)
      .then((response) => {
        console.log('response ',response)

        if (response?.data) {
          setPaciente(response?.data);
          setError(null);
        }
        setLoading(false);
      })
      .catch((response?.error) => {
        setError(response?.error);

        setErrormsg("No data");
        setLoading(false);
      });
  }, []);
  const handleClick = (id) => {
    navigate(`/edit/${id}`);
  };
  return (
    <>
      <Header />
      {loading && (
        <div className="loader-container">
          <Loader />
        </div>
      )}
      <div className="container">
        <table className="table table-dark table-hover">
          <thead>
            <tr>
              <th scope="col">ID</th>
              <th scope="col">DNI</th>
              <th scope="col">NOMBRE</th>
              <th scope="col">TELEFONO</th>
              <th scope="col">CORREO</th>
            </tr>
          </thead>
          <tbody>
            {paciente.length > 0? (
              paciente?.map((data, i) => {
                return (
                  <tr key={i} onClick={() => handleClick(data.PacienteId)}>
                    <td>{data.PacienteId}</td>
                    <td>{data.DNI}</td>
                    <td>{data.Nombre}</td>
                    <td>{data.Telefono}</td>
                    <td>{data.Correo}</td>
                  </tr>
                );
              })
            ) : (
              <tr>
                <td colSpan="5">{errormsg}</td>
              </tr>
            )}
          </tbody>
        </table>
      </div>
    </>
  );