Preact and Fetch API

Test the Fetch API using preact and bootstrap.

by Leolloyd Andrade

HTML

<link rel="stylesheet" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
<div id="app" class="container"></div>

CSS

#app {
  padding-top: 15px;  
}

.red-border {
  border: 1px solid red;
}

.blue-border {
  border: 1px solid blue;
}

.green-border {
  border: 1px solid green;
}

Preact

/* @jsx h */
const { Component, h, render } = preact;

class MyApp extends Component {
	constructor(props) {
  	super(props);
    this.state = { 
    	name: 'Leo',
      status: 0
    };
    //this.clickHandler = this.clickHandler.bind(this);
    this.fetchButtonHandler = this.fetchButtonHandler.bind(this);
    this.resetClickHandler = this.resetClickHandler.bind(this);
  }
  
  render(props, { name }) {
		{/* <ParentClickTest onclick={this.clickHandler} /> */}
    
  	return (
    	<FetchTest onclick={this.fetchButtonHandler}>
        <p>{`Status: ${this.state.status}`}</p>
        <p><a onclick={this.resetClickHandler} href="#">Reset</a></p>
      </FetchTest>
    );
  }
  
  resetClickHandler(e) {
  	this.setState({status: 0});
  	e.preventDefault();
  }
  
  async fetchButtonHandler(e) {
		const result = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    this.setState({status: result.status});
    console.log(result);  
  }
  
  clickHandler(e) {
  	let t = e.target;
    do {
    	if (t.classList.contains('js-item')) {
      	e.stopPropagation();
      	t.innerHTML = `Hi`;
        break;
      }
    } while ((t = t.parentNode));
  }
}

const FetchTest = ({...props}) => (
  <div>
    <button class="btn btn-primary" {...props}>Fetch API Test</button>
    {props.children}
  </div>
);

const ParentClickTest = ({...props}) => {
	return (
    <div class="row" {...props}>
      <div class="col-sm-4 red-border js-item">
        1 of 3
      </div>
      <div class="col-sm-4 blue-border js-item">
        2 of 3
      </div>
      <div class="col-sm-4 green-border js-item">
        3 of 3
      </div>
    </div>  
  );
};

render(<MyApp />, document.querySelector("#app"));