D
D
dimasgfree2019-11-04 12:49:18
JavaScript
dimasgfree, 2019-11-04 12:49:18

Why is the data from the 'options' state not output?

import React, { Component } from 'react';
import axios from 'axios';

export default class App extends Component {
  state = {
    searchValue: '',
    options: [],
    roots: [],
  }

  componentDidMount () {
    axios.get(`https://swapi.co/api/`)
      .then(data => {
        var arr = [];
        for (var key in data.data) {
          arr.push(data.data[key]);
        }
        this.setState({ roots: arr });
      })
      .catch(err => console.log('Error: ', err));
  }

  onSearchChange = event => {
    this.setState({ searchValue: event.target.value });
    if (event.target.value.length >= 3) {
      let newData = [];
      this.state.roots.map((root) => {
        axios.get(`${root}?search=${this.state.searchValue}`)
          .then(data => { 
            data.data.results.map((item) => {
              const rootName = root.split('/');
              const searchItem = {
                name: item.name,
                rootName: rootName[4],
              }
              newData.push(searchItem)
            });
          })
          .catch(err => console.log('Error: ', err));
      })
      this.setState({ options: newData });
      console.log(this.state.options);
    }
  }

  render() {
    return (
      <div>
        <input value={this.state.searchValue} onChange={this.onSearchChange} />
        { this.state.options ?
          <div className="options__list">
            { this.state.options.map( (item, index) => {
              return (
                <div
                  key={ index }
                  className="options__item"
                >
                  <span className="options__text">
                    {item.name} - {item.rootName}
                  </span>
                </div>
              );
            } ) }
          </div> : null
        }
      </div>
    )
  }
}

Options state data is not displayed, but if you delete what you entered, it seems that the data of the last request is shown. I can't figure out what exactly I'm doing wrong.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
S
Sergey Sokolov, 2018-09-26
@Panda21

The difference is when the code is executed.
The first two lines are executed immediately when the document is loaded. The variable numis assigned the value of an empty input at that time.
The event listenerbtn is hung on. It is not executed immediately, but sits and waits for the event. Each time an event occurs, the internal code of the function is executed. The code inside the function - this one - is executed later when the button is pressed. Displays the value defined at the very beginning in a square. Or it takes a fresh, "for now" value from input'a in the second version of the code with "if instead of num, substitute document.get ...". getSquareNum()
alert()num

D
dollar, 2018-09-26
@dollar

Because num is a copy of the element's value.
It's better to make num be a pointer to the element itself:

var num = document.getElementById("number"); //здесь value опускаем
var btn = document.getElementById("btn");
 
btn.addEventListener("click", function() {
  alert(num.value*num.value); //получаем текущее значение
});

0
0xD34F, 2019-11-04
@dimasgfree

Execute setState before receiving a response (method onSearchChange).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question