Pagination

emilo Post Leave a Comment

import React from 'react';
import ReactDOM from 'react-dom';
import axios from 'axios';
class ReactPagination extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      myArray: [],
      first: 0,
      last: 10,
    }
  }
  async componentDidMount() {
    try {
      const response = await axios.get('https://jsonplaceholder.typicode.com/comments');
      var responseData = response.data;
      var myArray = this.state.myArray;
      for (var obj of responseData) {
        myArray.push(obj.name);
      }
      this.setState({ myArray: myArray });
    } catch (error) {
      console.error(error);
    }
  }
  next() {
    var last = this.state.last;
    if (last >= this.state.myArray.length) {
      console.log("gereg");
    }
    else {
      var double = this.state.last + 10;
      var half = this.state.first + 10;
      this.setState({last: double});
      this.setState({first:half});
    }
  }
  prev() {
    var first = this.state.first;
    if (first < 1) {
      console.log("ewgeg");
    }
    else {
      var double = this.state.last - 10;
      var half = this.state.first - 10;
      this.setState({last: double});
      this.setState({first:half});
    }
  }
  render() {
var myArray = this.state.myArray;
var tags = [];
for (var i = this.state.first; i < this.state.last && i < myArray.length; i++) {
var obj = myArray[i];
tags.push(<div key={i}>{i+1} {obj}</div>);
}
    return (
      <React.Fragment>
        {tags}
        <button onClick={this.prev.bind(this)}>PREV</button>
        <button onClick={this.next.bind(this)}>NEXT</button>
      </React.Fragment>
    );
  }

}
ReactDOM.render(<ReactPagination />, document.getElementById('root'));