Home > Blockchain >  This code doesn't show a compile error, but the console won't render
This code doesn't show a compile error, but the console won't render

Time:10-28

import React from 'react';

const url = 'https://randomuser.me/api/?results=10'

async function List() {

    const data = await fetch (url)
    const response = await data.json()

    return (
        <div>
            {response.map((item)=>(
            <div>{item.results[1].name.first}</div>
            ))}
        </div>
        
    )
}

It also throws this: The above error occurred in the component:

at List
at div
at App

Consider adding an error boundary to your tree to customize error handling behavior. Visit https://reactjs.org/link/error-boundaries to learn more about error boundaries.

CodePudding user response:

If you working with a functional component. You need to use React hooks for API calls. You can use useEffect hooks to call the API.

Example:

const { useState } = React;

function useFetchData() {

  const [data, setData] = React.useState([]);

  React.useEffect(() => {
    return fetch("https://randomuser.me/api/?results=10")
      .then((response) => response.json())
      .then((responseJson) => {
        setData(responseJson.results);
      })
      .catch((error) => {
        console.error(error);
      });
  }, []);

  return { data };
}

function App() {

  const { data } = useFetchData();

  return (
    <div id="quote-box">
      {data.map((item) => (
        <div>{item.name.first}</div>
      ))}
    </div>
  );

}

ReactDOM.render(
  <App />,
  document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Calling an API inside a component is a side effect and React doesn't want that. React components expect you to provide the data and render that data immediately. If you want to call an API before rendering the component, use a side effect method like useEffect() and call that API inside the lambda. The component now knows that there is an expected side effect and will re-render once the data has updated.

  • Related