A
A
aznhautroalvyl2018-10-15 09:09:16
JavaScript
aznhautroalvyl, 2018-10-15 09:09:16

Populate input field from json?

The id value comes to the component, according to which it is necessary to display the value corresponding to it in the input. The data to fill comes from the fetch request and is stored as {id: 1, value: 'Test'}.
In fact, input remains empty.
Tried adding async / await - didn't
work

class TestPage extends Component {
  constructor(props) {
    this.state = {     
      data: []
    };   
  }

  async componentDidMount() {  
    this.getValueForInput();
  }

  getValueForInput() { 
    this.onHandleFetch(this.props.params.idValue); // передача id
    console.log(this.state.data); // здесь не выводятся данные
    return this.state.data.value; // возвращаем значение, полученное по id
  }

  onHandleFetch(id) {
    fetch( ... )
      .then(newData =>
        this.setState({ data: newData }) // получаем значение вида [{id: 1, value: 'Test'}]
      );
  }

  render() {
    console.log(this.state.data); // здесь выводятся данные
    return (
     ...
              <InputForm getValueForInput={this.getValueForInput} data={this.state.data}
     ...        
}

input:
class InputForm extends Component {
  constructor(props) {
    super(props);
    this.state = {
      value1: ''
    };
    ...
  }

  componentDidMount() {
    this.setValue(); // установить значение в input
  }

  setValue() {
    console.log(this.props.getValueForInput()); // ничего нет
    this.setState({ value1: this.props.getValueForInput() });   
  }

  render() {
   ...
            <input  type='text' required value={this.state.value1}  />       
 ... }    
InputForm.propTypes = {
  getValueForInput: PropTypes.func,
  data: PropTypes.array
};      
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir Proskurin, 2018-10-15
@aznhautroalvyl

No need to copy component props to local state. Remove setValue, just work with props.data reactively.
In addition, your onHandleFetch is an asynchronous method, and you are trying to get the result of its work immediately

getValueForInput() { 
    this.onHandleFetch(this.props.params.idValue); // передача id
    console.log(this.state.data); // здесь не выводятся данные
    return this.state.data.value; // тут тоже не получается значение, т.к. onHandleFetch его еще не успел подготовить
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question