0

I am trying to set state to particular index of array.

   let updatedArray = [...this.state.AnswerState];
   updatedArray[name] = value;
   this.setState({
        AnswerState: [updatedArray]
   }, () => {
        console.log(this.state.AnswerState);
   });

I have

this.state.AnswerState = [ 
                           0: {Name: ""}
                           1: {Number: ""}
                         ]

which is dynamically generated. How should I update the state? I am getting output as nested loops:

0: Array(1)
 0: {Name: ""}
    Name: "s"
 Name: "ss"

and so on..

I want that my state should update on accepting input as below:

AnswerState = [
    Name: aaa, Number: bbbb
]
Shraddha J
  • 714
  • 9
  • 17

1 Answers1

0

Setting state to a particular index of array.

Here I am putting element at index 1 in updated array.

import React from "react";
import ReactDOM from "react-dom";

class App extends React.Component {
  state = {
    answerState: [{ name: "something1" }, { name: "something2" }]
  };
  handleSubmit = () => {
    const index = 1;
    let updatedArray = new Array(this.state.answerState[index]);
    this.setState({
      answerState: updatedArray
    }, () => {
      console.log(this.state.answerState)
    })
  };
  render() {
    return (
      <>
        <button onClick={this.handleSubmit}>Click Me</button>
        <br />
        {this.state.answerState[0].name}
      </>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Hope it helps!!!

tarzen chugh
  • 10,561
  • 4
  • 20
  • 30
  • It is only accepting one key value pair first time and after that undefined comes in state – Shraddha J Sep 27 '19 at 11:03
  • Because next time there would be only single element in array and there is no element at index 1. So undefined, this example was to show how to update state by index. – tarzen chugh Sep 27 '19 at 11:09
  • @tarzn chugh But I want index as string. And there can be multiple elements in array. – Shraddha J Sep 30 '19 at 06:20
  • Array have index as number, if you want index as string you will have to use object which has key value pair. See [this](https://stackoverflow.com/questions/9526860/why-does-a-string-index-in-an-array-not-increase-the-length) link for more info. – tarzen chugh Sep 30 '19 at 06:39