0

I have made a React page. It initially gets data from my API, and stores it in state. The parent component makes a TextInput in a component for each row of data.

The TextInput value is from a prop. The onChange calls a method on the parent (through a prop given to the TextInput), which finds the appropriate index to update, updates it, then setState. It also sends a PUT to my API to update the data.

However it is pretty sluggish when typing. I can type fast and you can see it having a delay sometimes.

Any ideas?

update_sound(sound_transcript, sound_id) {
  var index = this.state.board.sounds.findIndex(sound => {
    return sound.id === sound_id;
  });

  this.state.board.sounds[index].sound_transcript = sound_transcript;
  this.setState({
    board: this.state.board
  });

  axios
    .put("/api/v1/sounds/" + sound_id, {
      sound_transcript: sound_transcript
    })
    .then(response => {
      //Handle success
      console.log("Update success");
    })
    .catch(error => {
      //Handle error
      console.log("Update error: " + error);
    })
    .then(() => {
      //Always executed
    });
}

<textarea
  className="soundPlayer_text_input"
  value={this.props.sound.sound_transcript}
  onChange={this.soundOnChange}
/>;

soundOnChange(event) {
  console.log("soundOnChange");
  this.props.update_sound(event.target.value, this.props.sound.id);
}

Thanks

6
  • 1
    You are making a remote request in every keystroke. It is better to change your logic somehow. Also, do not mutate your state like this: this.state.board.sounds[index].sound_transcript = sound_transcript;
    – devserkan
    Commented Sep 23, 2018 at 22:44
  • Should I try to figure out immutability-helper, or make a copy and change that?
    – Grapehand
    Commented Sep 24, 2018 at 0:00
  • copy is a thing you should avoid in React/Redux/Anything_else_you_dont_want_mutation. For example, forget about direct assigning (never do this!), even Object.assign, or spread syntax or methods like .map only do shallow copies. If you change a nested property in the copied object then you will mutate the original one. So, you need to combine all those methods. I can't say much about immutability-helper since I don't use it. But, if you learn the basics and best practices you won't need it.
    – devserkan
    Commented Sep 24, 2018 at 0:08
  • So how do you change data if you're changing state? Idk how to even ask these questions, it is starting to become demented
    – Grapehand
    Commented Sep 24, 2018 at 0:27
  • I tried this.setState((state) => ({ [state.board.sounds[index].sound_transcript]: sound_transcript })); which I w
    – Grapehand
    Commented Sep 24, 2018 at 0:35

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Browse other questions tagged or ask your own question.