React Class Component - Fetch (Ajax)

About

React - Fetch in a class component

Example

class MyComponent extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: null,
      isLoaded: false,
      items: []
    };
  }

  // /doc/json/items.json is the api endpoint
  componentDidMount() {
    fetch("/doc/json/items.json")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // 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.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

  render() {
    const { error, isLoaded, items } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <ul>
          {items.map(item => (
            <li key={item.name}>
              {item.name} {item.price}
            </li>
          ))}
        </ul>
      );
    }
  }
}
  • Rendering
ReactDOM.render(
  <MyComponent/>,
  document.getElementById('root')
);
  • The standard mandatory “root” DOM node (placeholder for React DOM manipulation)
<div id="root"></div>
  • Output:

Documentation / Reference





Discover More
Chrome Devtool Xhr Fetch Request
Browser - Ajax (Asynchronous JavaScript And XML)

Asynchronous Javascript and XML (Ajax) is just a name umbrella to talk a technology that retrieve data from a server asynchronously. Ajax Every Ajax call is using: a XMLHttpRequest (XHR) request...
React - Fetch

in react that fetch data from an API endpoint Class Component: see Function Component: see
React - Proxy to a backend

How to proxy request to a backend in React. To tell the development server to proxy any unknown requests to your API server in development, add a proxy field to your package.json, for example: ...
React Hook Side Effect Doc Title
React Function Component - (Side) Effect (useEffect Hook)

Effect Hook is a hook that lets you perform side effects in functional components, and is similar to lifecycle methods in classes. An effect is also known as a side-effect Example of effect: Data...
What are React Hooks?

hooks are functions that: let you hook into React state and lifecycle features from function components. can be used only in a functional component (ie not inside classes component) may call other...



Share this page:
Follow us:
Task Runner