DEV Community

Edrick Ee
Edrick Ee

Posted on • Edited on

Quick react setup without Hook

Import React

import React from 'react';
Enter fullscreen mode Exit fullscreen mode

Create Class

Class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isLoaded: false,
      list: null,
      error:false
    }
  }
Enter fullscreen mode Exit fullscreen mode

Create componentDidMount to fetch data from API

componentDidMount() {
  fetch("http://localhost:3000/example")
    .then(res => res.json())
    .then(
      (result) => {
        this.setState({
          listen:result,
          isLoaded: true
        });
      },
      (error) => {
        this.setState({
          error: true,
          isLoaded: true
        })
      }
    )
}
Enter fullscreen mode Exit fullscreen mode

Render component & Post request (I am requesting Post & Get at the same time so I can keep up the new data after Post request)

 render() {

    const postRequest = (data) => {
      let requestOptions = {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
      };
      fetch("http://localhost:3000/example", requestOptions)
      fetch("http://localhost:3000/example")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            list: result,
            isLoaded: true
          });
        },
        (error) => {
          this.setState({
            error: true,
            isLoaded: true
          })
        }
      )
    }

    const { error, isLoaded, list } = this.state;
    if (error) {
      return <div>Error: {error.message}</div>;
    } else if (!isLoaded) {
      return <div>Loading...</div>;
    } else {
      return (
        <div>Hello, World~!</div>
      );
    }
  }
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Top comments (0)