skip to Main Content

I am new to react and I’m working on react fetch using useEffect.
I have a util file which fetches data from an API. I am testing the sad path and the API returns a 400 status code.
below is my fetch code:

export async function getVans() {
  const res = await fetch("/api/vans")
  if (!res.ok) {
  throw Object.assign(new Error("Failed to fetch vans"),{
      message: "Failed to fetch vans", 
      statusText: res.statusText,
      status: res.status
  });
 }
  const data = await res.json()
  return data.vans
}

I’m using this in my component to set some states.

I’m using a try-catch block while calling this API inside the use effect. But I see that the error is not caught.

useEffect(() => {
async function loadVans() {
  setLoading(true)
  try {
      const data = await getVans()
      console.log("fetched data: "+data);
      setVans(data)
  } catch (err) {
    console.log("error :"+err)
      setError(err)
  } finally {
      setLoading(false)
  }
}
loadVans()
}, [])

I see it proceeds and breaks with runtime errors.
Here is the link to the project :https://github.com/manjosh1990/react-practice/tree/master/reactive-navigation

I get the error on /vans path.
the file is Vans.jsx
Please advise.

3

Answers


  1. AJAX and APIs – React:

    Note: it’s important to handle errors here

    instead of a catch() block so that we don’t swallow

    exceptions from actual bugs in components.

    Login or Signup to reply.
  2. import { useEffect } from "react";
    
    // simulate api call
    export async function fetchRandomUser() {
      const response = await fetch("https://randomuser.me/api/");
      // If response is ok
      if (response.ok) {
        return response.json();
      } else {
        // else throw your custom error message
        throw new Error("error");
      }
    }
    
    
    export default function App() {
      useEffect(() => {
        async function fetchUsers() {
          try {
           // call user's api
            const users = await fetchRandomUser();
            console.log(users.results);
          } catch (error) {
            // handle error
            console.log("Error", error.message);
          }
        }
        fetchUsers();
      }, []);
      return (
        <div className="App">
          <h1>Hello CodeSandbox</h1>
        </div>
      );
    }
    Login or Signup to reply.
  3. Check out this CodeSandbox that catches the error for your getVans function.

    import React, { useEffect, useState } from "react";
    import "./styles.css";
    
    async function getVans() {
      throw Object.assign(new Error("Failed to fetch vans"), {
        message: "Failed to fetch vans"
      });
    }
    
    export default function App() {
      const [counter, setCounter] = useState(1);
    
      useEffect(() => {
        async function loadVans() {
          try {
            const data = await getVans();
            console.log("fetched data: " + data);
          } catch (err) {
            console.log("error :" + err);
          } finally {
          }
        }
        loadVans();
      }, [counter]);
    
      const onClick = () => {
        setCounter(counter + 1);
      };
      return (
        <div className="App">
          <button onClick={onClick}>click me trigger caught error</button>
        </div>
      );
    }
    

    I wish I could pinpoint what the error is, but it’s hard without a "working" example from your end.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search