0

I have defined an array as below

 constructor() {
    super();
    this.state = {
       resultingName : []
    };
}

After this, I perform all the operation, get the response and then push to a temporary array

let tmpArray = [];
for (var i = 0; i < response.data.names.length; i++) {
          tmpArray.push(response.data.names[i]);
        }

Now, the data is present in the tmpArray.

What is the way that I can assign this to my initial resultingName array?

These are the ways that don't work

this.setState({
    resultingName: this.state.resultingName.concat(tmpArray)        
 });

Also,

this.setState({ resultingName: [...this.state.resultingName, ...tmpArray] })

doesn't work.

What is the best way to assign to the array, since I need the data in other functions of the component.

Also, I want to display the contents of the resultingName array on the console. How do I do that?

4
  • at the time when you have the response, instead of looping you can directly use setState no need of extra calculations this.setState({ resultingName: [...this.state.resultingName, ...response.data.names] }) Commented Sep 17, 2019 at 4:25
  • you can the same data in another function with state resultingName Commented Sep 17, 2019 at 4:26
  • @Harish - this doesn't work and gives the error Cannot read property 'setState' of undefined Also, the array will be null Commented Sep 17, 2019 at 4:31
  • 1
    here your this is not pointing to class. check this and it will run as aspected Commented Sep 17, 2019 at 4:53

5 Answers 5

0
    constructor() {
        super();
        this.state = {
           resultingName : []
        };
    }

    let tmpArray = [];
    for (var i = 0; i < response.data.names.length; i++) {
          tmpArray.push(response.data.names[i]);
      }
    this.setState({resultingName : tmpArray})
Sign up to request clarification or add additional context in comments.

3 Comments

This is the solution I have right now. I need to assign tmpArray into resultingName and use that. Thats the solution I'm looking for
Sorry My laptop shut down
this causes an issue Cannot read property 'setState' of undefined at the setState. I believe it is because the setState is inside the .then part of the axios request
0

Simply push element in resultingName copy.

let tmpArray = [...this.state.resultingName];
for (var i = 0; i < response.data.names.length; i++) {
     tmpArray.push(response.data.names[i]);
}

this.setState({ resultingName: tmpArray })

Comments

0

If you want to render every loop in array, use setstate instead of tmparray. But for one render issue setState{(yourarray : tmparray)}

Check it out here

How to update array state in react native?

Comments

0

Try to use arrow function on onclick function

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

import "./styles.css";

class App extends React.Component {   constructor() {
    super();
    this.state = {
      resultingName: []
    };   }

  handleClick = () => {
    const names = ["joe1", "joe2", "joe3", "joe4", "joe5"];
    let tmpArray = [];
    for (var i = 0; i < names.length; i++) {
      tmpArray.push(names[i]);
    }
    // this.setState({
    //   resultingName: this.state.resultingName.concat(tmpArray)
    // })
    this.setState({
      resultingName: [...this.state.resultingName, ...tmpArray]
    });   };   render() {
    return (
      <div className="App">
       <button onClick={()=>this.handleClick()}>Click me</button>
        <div>{this.state.resultingName}</div>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    );   } }

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

1 Comment

By using arrow function component this will be preserved in called function.
0
class TodoApp extends React.Component {
  constructor(props) {
    super();
    this.state = {
       resultingName : []
    };`enter code here`
  }
  componentDidMount(){
    let tmpArray = [];
  for (var i = 0; i <10; i++) {
          tmpArray.push(`arraypushtest-${i}`);
        }
  this.setState({
    resultingName: this.state.resultingName.concat(tmpArray)        
   }); 
   // another format 
 this.setState({ resultingName: [...this.state.resultingName, ...tmpArray] })
 //another format 
 let tmpArray1 = this.state.resultingName;
  for (var i = 0; i <10; i++) {
          tmpArray1.push(`arraypushtest-${i}`);
        }
        this.setState({resultingName:tmpArray1}) 
  }

  render() {
  console.log('this',this.state)
    return(
<h1>ArrayPUshElement</h1>)
  }
}

ReactDOM.render(<TodoApp />, document.querySelector("#app"))

The format you told is working fine using the lifecycle function by componentDidMount() method or callback function. Hope this will work fine:)

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.