user7370565
user7370565

Reputation:

how to push a new element into an array from the state

I'm trying to push in elements into an array called 'this.state.tags'. On the console, I see the elements pushing into the array. However, when I add something, the array comes out blank, when I add more items I only the see the previous items I've added. I'm not seeing the newest item I've pushed in.

I've done Object.assign([], this.state.tags) from the child component Grades.js. Then I pushed in 'this.state.newTag' and I've reset the state to that new result.

//From Grades.js, the child component

    state = {
        toggle: null,
        newTag: '',
        tags: []
    }

    addTags = (event) => {
        event.preventDefault();

        let newTagArr = Object.assign([], this.state.tags)
        newTagArr.push(this.state.newTag)

        this.setState({
            tags: newTagArr
        }) 

        // this will pass on to the parent
        this.props.filterTags(this.state.tags)
    }

    render() {
        const { tags } = this.state

        let tagList = tags.map((item, index) => {
            return (
                <li key={index} className="tagListItem">{item}</li>
            )
        })

        return(
           <div>
               <ul className="tagList">{tagList}</ul>

                        <form onSubmit={this.addTags}>
                            <input 
                                placeholder="Add a tag" 
                                name="newTag"
                                onChange={this.handleInput}
                                style={{border: '0', borderBottom: '1px solid #000'}} 
                            />
                        </form>
           </div>
        )
    }

// From App.js, the parent component

  state = {
    students: [],
    filteredStudents: [],
    filteredByTag: [],
    search: '',
    tag: '',
    toggle: false
  }

  componentDidMount() {
    axios.get('https://www.hatchways.io/api/assessment/students')
    .then(result => {

      let newArr = Object.assign([], result.data.students);
      let newResult = newArr.map(elem => {
        return {city: elem.city, company: elem.company, email: elem.email, 
          firstName: elem.firstName.toLowerCase(), lastName: elem.lastName.toLowerCase(),
          grades: elem.grades, id: elem.id, pic: elem.pic, skill: elem.skill}
      })

      this.setState({
        students: newResult
      })

    })
    .catch(err => console.log(err))
  }

  tagFiltering = (param) => {
    console.log(param)
    this.state.students.push()
  }

I expect the output to be ["tag1", "tag2", "tag3"]
Not ["tag1", "tag2"], when I've already typed in tag1, tag2 and tag3

Upvotes: 0

Views: 98

Answers (1)

belSalah
belSalah

Reputation: 43

Use ES2015 syntax :

this.setState({
    tags: [...this.state.tags , this.state.newTag]
}) 

In react the state is immutable meaning that we have to provide new state object every time, we call the setState method.

Upvotes: 4

Related Questions