O
O
Oleg Parfenyuk2019-02-25 16:08:13
JavaScript
Oleg Parfenyuk, 2019-02-25 16:08:13

How to implement imitation of requests to the server (Promise + setTimeout)?

I started learning react and ran into the problem of simulating requests using promises.
How can they be used specifically in this component?

import React, { Component } from 'react';
import AddNewPerson from './AddNewPerson';
import myData from './ParticipantsList.json';
import List from './List';
import _ from 'lodash';

import './style/style.css';
var Plists=myData.Participants;
var toggle=1;
export default class App extends Component {

  constructor(props){
    super(props);
    this.state={
      Plists
    }
    let promise = new Promise((resolve, reject) => {

      setTimeout(() => {
        // переведёт промис в состояние fulfilled с результатом "result"
        resolve("addPerson");
      }, 1000);
    
    });
    promise
  .then(
    addPerson => {
      // первая функция-обработчик - запустится при вызове resolve
      console.log("Fulfilled: " + addPerson); // result - аргумент resolve
    },
    error => {
      // вторая функция - запустится при вызове reject
      alert("Rejected: " + error); // error - аргумент reject
    }
  );
  }

  render() {
    return (
      <div className="App">

        <main className="App-main">
          <h2>Table</h2>        
          <AddNewPerson addPerson={this.addPerson.bind(this)}
                        Plists={this.state.Plists}/>        
          <List Plists={this.state.Plists}
                savePerson={this.savePerson.bind(this)}
                deletePerson={this.deletePerson.bind(this)}
                sortByName={this.sortByName.bind(this)}
                sortByEmail={this.sortByEmail.bind(this)}
                sortByPhone={this.sortByPhone.bind(this)}                
                />        
        </main>
      </div>
    );
  }

  addPerson(name,email,phoneNumber){
    this.state.Plists.unshift({
      name,
      email,
      phoneNumber
    });
    this.setState({ Plists:this.state.Plists})
  }
  
  savePerson(oldPerson,newPerson){
    const findPerson =_.find(this.state.Plists, Plist =>Plist.name === oldPerson);
    findPerson.name = newPerson.name;
    findPerson.email= newPerson.email;
    findPerson.phoneNumber=newPerson.phoneNumber;
    this.setState({Plists: this.state.Plists});
  }

  deletePerson(personToDelete){
    _.remove(this.state.Plists,Plist=>Plist.name ===personToDelete);
    this.setState({Plists:this.state.Plists});
  }
  
  sortByName(){    
    if (toggle===1){
      this.setState({Plists: _.orderBy(this.state.Plists,['name'],['asc'])});      
      toggle*=-1;}
    else {
      this.setState({Plists: _.orderBy(this.state.Plists,['name'],['desc'])});
      toggle*=-1;}
    }
    
  
  sortByEmail(){
    if (toggle===1){
      this.setState({Plists: _.orderBy(this.state.Plists,['email'],['asc'])});      
      toggle*=-1;}
    else {
      this.setState({Plists: _.orderBy(this.state.Plists,['email'],['desc'])});
      toggle*=-1;}
  }
  sortByPhone(){
    if (toggle===1){
      this.setState({Plists: _.orderBy(this.state.Plists,['phoneNumber'],['asc'])});      
      toggle*=-1;}
    else {
      this.setState({Plists: _.orderBy(this.state.Plists,['phoneNumber'],['desc'])});
      toggle*=-1;}
  }
  
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
H
hzzzzl, 2019-02-25
@id_oleg_parfenyuk

state = { loaded: false, data: null }

const getData = () => new Promise(resolve => {
  setTimeout(() => resolve( {data: 177} ), 2000)
})

...

getData().then(d => {
  // что то делаем с данными, например
  this.setState( { loaded: true, data: d } )
})

render() {
  if (!this.state.loaded) return <Loading />
  return <MyBeautifulDataComponent />
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question