Home > Software design >  API - JSON fetch returning empty results
API - JSON fetch returning empty results

Time:07-11

I'm trying to fetch an API from a URL using create-react-app but my code keeps returning an empty list equal to the number of fetched arrays. Suggestions?

  ...
  const [error, setError] = useState(null);
  const [isLoaded, setIsLoaded] = useState(false);
  const [items, setItems] = useState([]);

  useEffect(() => {
    fetch("URL")
      .then(res => res.json())
      .then(
        (result) => {
          setIsLoaded(true);
          setItems(result);
        console.log(result);
        },
        (error) => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

  if (error) {
    return <div>Error: {error.message}</div>;
  } else if (!isLoaded) {
    return <div>Loading...</div>;
  } else {
    return (
      <ul>
        {items.map(item => (
          <li key={item.id}>
          </li>
  ...

JSON sample:

[
    {
        "id": xxxxx,
    },
        "order": x,
 .....

CodePudding user response:

Change your useEffect to this

useEffect(() => {
    fetch("URL")
      .then(res => {
          setIsLoaded(true);
          setItems(res.json());
          console.log(result);
      })
      .catch(error => {
          setIsLoaded(true);
          setError(error);
        }
      )
  }, [])

CodePudding user response:

enter image description here

how did you got result here

do this instead

fetch("url")
.then(res=>{
console.log(res.json()); //to view if the data you recieved in response is correct or not
setIsLoaded(true);
setItems(res.json());
console.log(Items); //state you created for setItems
)}

CodePudding user response:

instead of using useEffect hook and write a lot of lines, you can simply use useSWR library.

Example of code:

import useSWR from 'swr'

function Profile() {
  const { data: userData, error: userError } = useSWR('/api/user', fetcher)
  const { data: userInfo, error: userInfoError} = useSWR('/api/userInfo', fetcher)

  if (userError || userInfoError) return <div>failed to load</div>
  if (!userData || !userInfo) return <div>loading...</div>
  return <div>hello {userData.name}, birthDate: {userInfo.birthDate}!</div>
}
  • Related