React Class Component - Fetch (Ajax)

> (World Wide) Web - (W3|WWW) > Javascript (Js|ECMAScript) > React > Class Component

1 - About

Advertising

3 - 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:

4 - Documentation / Reference

web/javascript/react/class/fetch.txt · Last modified: 2019/06/17 13:25 by gerardnico