Salmon46420
Salmon46420

Reputation: 1

How do I push and object into a state that is an array?

I am making a react app and whenever I submit it gives me the error "TypeError: Cannot read property 'map' of undefined". I assume this happens because whenever I use this.setState, instead of just pushing a value into my array state, it completely overrides the array with that value. How do I just push a value into my array state without it just overriding my array?

Upvotes: 0

Views: 144

Answers (3)

Saeed Hemmati
Saeed Hemmati

Reputation: 505

For class components:

class Component extends React.Component {
  this.state = { x: 0 };

  const increaseValue = () => {
    this.setState((preValue) => ({
      ...preValue,
      x: preValue.x + 1
    }))
  }

  render() {
    return (
      <button onClick={increaseValue}>click</button>
    )
    
  }
}

Also, I recommend to you which using function components and hooks for more efficiency and more elegant coding.

function Component = () => {
  const [number, setNumber] = useState({ number: 0 });
 
  const increaseValue = () => {
    setNumber(preValue => ({ ...preValue, number: preValue.number + 1 }))
  }

  return (<button onClick={increaseValue}>click</button>)
}

Upvotes: 0

Mint
Mint

Reputation: 1059

Try this code:

this.setState = [...state, value]

Upvotes: 1

amit kumar
amit kumar

Reputation: 21

I thin you need to check the data first like this:

const [happyData, setHappyData] = useState([])
    
        data = [
          {
            "userId": 1,
            "id": 1,
          },
        {
            "userId": 2,
            "id": 3,
          }]
    // check data is there or not 
        data && data.map((item)=>{
        //do something
    })

    // for pushing data 
    setHappyData((happyData)=>{
    ...happyData, data

})

Upvotes: 0

Related Questions