1

I'm trying to render API data but for some reason, I'm unable to do it.

const [ data, setData ] = useState([])

  const fetchData = () => {

    return (
      fetch('https://mocki.io/v1/b9c63035-97c5-40a0-b45c-2abdf5261bdf')
      .then(response => response.json())
      .then(data => setData(data))
      .catch(error => {
        console.log('Error fetching and parsing data', error)
      })
    )
  }

useEffect(() => {
     fetchData()
  }, []);

console.log('API DATA', data) I'm getting the response back but I'm not sure why its not able to loop through. I guess its because the data is in JSON format?

return (
 {       
   data.length > 0 && data.map((item, index) => {
    <div key={index}>{item.title}</div>
   })
 }
)

enter image description here

3
  • what does your data look like? Commented Feb 2, 2022 at 5:49
  • @IamL updated the post with the data. Commented Feb 2, 2022 at 5:52
  • just remove that return inside fetchData function, no ned to return API call there Commented Feb 2, 2022 at 5:52

2 Answers 2

6

You aren't returning anything after mapping through the array, update your return statement as:

  return (
    <>
      {data.length > 0 &&
        data.map((item, index) => {
          return <div key={index}>{item.title}</div>;
        })}
    </>
  );

or

 return (
    <>
      {data.length > 0 &&
        data.map((item, index) => <div key={index}>{item.title}</div>)}
    </>
  );

Also, JSX expressions should have only one parent element. Ensure wrapping the return in a fragment, i.e, <>

Sign up to request clarification or add additional context in comments.

Comments

1

I prefer axios and useRef for API

  const [myData, setMyData, myDataRef] = useStateRef([]);

  const getData = () => {
    axios
      .get("https://mocki.io/v1/b9c63035-97c5-40a0-b45c-2abdf5261bdf")
      .then((res) => {
        let data = res.data;
        console.log(data);
        setMyData(data);
      });
  };

  useEffect(() => {
    getData();
  }, []);



 <div>
    {myDataRef.current.length > 0 &&
      myDataRef.current.map((item, index) => {
        return <div key={index}>{item.title}</div>;
      })}
  </div>

Codesandbox

1 Comment

Really Appreciate it.

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.