dany
dany

Reputation: 21

render state after state is updated with response from axios

i wanna render state after i updated state with another response from api

on component did mount i make a request from random user and i store it in state, and i made a button which on click makes another request and stores another user from api in state , my problem is i cant seem to render the new state ( updated after click on button ) on console.log i see the updated state , but when i try to render , i get only the initial value , the rest appear as undefined

state = {
   persons : []
}

async componentDidMount( ){
     let response = await axios(`https://randomuser.me/api/?results=1`)
     this.setState({
       persons: response.data.results
     })
  }
update = async () => {
    const response = await axios(`https://randomuser.me/api/?results=1`)

    this.setState(prevState => ({
      persons: [...prevState.persons, response.data.results]
    }))
  }

render(){
    const test = this.state.persons.map( i => i.cell)
    return(
      <div>
      {test}
      <button onClick={this.update}>update</button>
      </div>
    )
  }

Upvotes: 0

Views: 51

Answers (2)

John Ruddell
John Ruddell

Reputation: 25842

You need to set the correct state. the response is an array, so you need to merge both arrays

update = async () => {
  const response = await axios(`https://randomuser.me/api/?results=1`)

  this.setState(prevState => ({
    persons: [...prevState.persons, ...response.data.results]
  }))
}

Upvotes: 2

Mahdi
Mahdi

Reputation: 1405

This should work

render(){
  const test = this.state.persons.map( i => {
    return(
      <div>{i.cell}</div>
    )
  })

  return(
    <div>
      {test}
      <button onClick={this.update}>update</button>
    </div>
  )
}

Upvotes: 0

Related Questions