user13193949
user13193949

Reputation:

Array.push() method replacing initial index value instead of appending at end

I'm trying to push new object values in array on every button click. Instead of this, it replaces the previous value. I think this problem is related to reference but can't seem to fix it.

var tranList = []
var newText, newAmount
const [Amount, setAmount] = useState("")
const [Text, setText] = useState("")
function textHandler(event) {
    newText = event.target.value;
    setText(newText)
}
function amountHandler(event){
    newAmount = event.target.value;
    setAmount(newAmount)
}
function clickHandler(){
    console.clear()
    var pair = {}
    pair["text"] = Text
    pair["amount"] = Amount 
    tranList.push(pair)
    // checking if object is pushed or not.
    tranList.map(item => {
        return console.log("Text: ", item.text, " Amount: ", item.amount)
     })
}

Upvotes: 0

Views: 1379

Answers (1)

Nadia Chibrikova
Nadia Chibrikova

Reputation: 5036

The problem is in the way you declare tranList

var tranList = []

Which means a brand new variable is created on each render. It is not that the value is replaced on click, it is being added to an empty array instead. What you need to do is to keep in the state

const [tranList , setTranList ] = useState([])

and add new values like

setTranList(list => [...list, newItem])

P.S. If you try to log tranList values immideatell after calling setTranList you'll notice it is always one step behind, which is expected behaviour, the updated state will be available in useEffect callback or/and on the next render.

Upvotes: 3

Related Questions