Categories
React

React Fetch Example, A Single JSON Object

A simple example how to get a single JSON object in React with fetch.

import React from 'react';

export default class App extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      error: null,
      isLoaded: false,
      data: [],
    }
  }

  componentDidMount() {
    fetch('http://ip.jsontest.com/').then(res => res.json()).then((result) => {
      this.setState({ isLoaded: true, data: JSON.stringify(result) });
    },
      (error) => {
        this.setState({ isLoaded: true, error });
      }
    );
  }

  render() {

    if (this.state.error) {
      return <div>Error: {this.state.error.message}</div>;
    } else if (!this.state.isLoaded) {
      return <div>Loading...</div>;
    } else {
      return this.state.data;
    }
  }
}

Result:

{"ip": "95.70.236.43"}