0

I am trying to use the method .contact() to push on element in my old_array to my new_array. I have one button on each element in the array like this:

´´´

<li key={i}>
   {{character.name} + "is" + {character.age} + "years old"}
   <button onClick={this.addToNewArray}>Fav</button>
</li>

´´´

so as you can see each element got a seperate id. Now i want to click the button to push that element to a new array . (i get data from API that i .map() into my old_array) My function looks like this:

´´´

constructor(props){
        super(props);
        this.state = {
            old_arary: [],
            new_array: []
        }
    }
addToNewArray = () => {
        let new_array = this.state.new_array.contact(this.state.old_array);
        this.setState({ new_array: new_array})

}

´´´

This is where i want my output:

´´´

<li>
   {this.state.new_array}
</li>

´´´

2
  • You are directly mutating the state which is not recommended when you are concating old_array and new_array. Instead you should be using setState method. Commented May 10, 2020 at 13:14
  • Now it seems to work BUT i get a huge error: gyazo.com/bb68e6fc3837f4ccc2e979305e48e379, it has something to do with the api? Commented May 10, 2020 at 13:30

1 Answer 1

3

First :

in your question , you are using contact() everywhere, and I think there is no such function for array in JS :) , that should be concat()

Second :

You can use ES6 for lower code, something like this:

let new_array = [...this.state.new_array , ...this.state.old_array];
this.setState({ new_array });

Third :

Change this

<li>
   {this.state.new_array}
</li>

To :

{
    this.state.new_array.map((obj,index) => (
        <li key={index}>
            {obj.name}
        </li>
    ))
}
Sign up to request clarification or add additional context in comments.

6 Comments

Now it seems to work BUT i get a huge error: gyazo.com/bb68e6fc3837f4ccc2e979305e48e379, it has something to do with the api?
I think you are not getting array, it might be object, try this let new_array = [...this.state.new_array , this.state.old_array]; if it works then its object and not array
Yes, it is objects im getting, i tried to change the output to {this.state.new_array.toString()} and i got [object Object],[object Object],... on my screen
@gospecomid12, that is array my friend, it would be great if you can create a demo and share link, have to debug, this way it won't be possible.
i actually made it work! i had to iterate over the array using map for it to display correctly.
|

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.