React API

emilo Post Leave a Comment

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import axios from 'axios';
class ReactAPI extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      randomJoke: "",
      Categories: [],
      catJoke: "",
      options: "animal",
      searchArr: [],
      searchValue: "animal"
    }
  }
  getRandomJoke() {
    axios.get(`https://api.chucknorris.io/jokes/random`)
      .then(res => {
        const response = res.data;
        this.setState({ randomJoke: response.value });
        this.setState({ randomImage: response.icon_url });
      })
  }
  async componentDidMount() {
    try {
      let response = await axios.get(`https://api.chucknorris.io/jokes/categories`);
      this.setState({ Categories: response.data });
    } catch (error) {
      console.error(error);
    }
  }
  getRandomCategoryJoke() {
    axios.get(`https://api.chucknorris.io/jokes/random?category=${this.state.options}`)
      .then(res => {
        const response = res.data;
        this.setState({ catJoke: response.value });
      })
  }
  changeOption(e) {
    this.setState({ options: e.target.value });
  }
  searchAll() {
    axios.get(`https://api.chucknorris.io/jokes/search?query=${this.state.searchValue}`)
      .then(res => {
        this.setState({ searchArr: res.data.result.map(obj => obj.value) });
      })
  }
  searchOnchange(e) {
    this.setState({ searchValue: e.target.value });
    this.searchAll();
  }
  render() {
    var categoriesHTML = this.state.Categories.map((item, index) =>
      <option key={index} value={item}>{item}</option>
    );
    var searchHTML = this.state.searchArr.map((item, index) =>
      <li className="item" key={index}>{item}</li>
    );
    return (
      <React.Fragment>
        <div className="container">
        <select value={this.state.options} onChange={this.changeOption.bind(this)}>{categoriesHTML}</select>
        <button onClick={this.getRandomCategoryJoke.bind(this)}>Get category joke</button>
        <button onClick={this.getRandomJoke.bind(this)}>Get random joke</button>
        <div>Random joke: {this.state.randomJoke}</div>
        <div>Category joke: {this.state.catJoke}</div>
        <input type="text" placeholder="search..." value={this.state.searchValue} onChange={this.searchOnchange.bind(this)}></input>
        <div className="pagination">{searchHTML}</div>
        </div>
      </React.Fragment>
    );
  }
}
ReactDOM.render(<ReactAPI />, document.getElementById('root'));