Every time a button is pressed, I would like to add an object containing a constant (amount) and the current date to an array.
for instance, if the button is pressed three times, the array should show this:
Array [
Object {
"amount": "5.00",
"date": "17/11/2020 22:26:16",
},
Object {
"amount": "5.00",
"date": "17/11/2020 22:26:17",
},
Object {
"amount": "5.00",
"date": "17/11/2020 22:26:18",
}]
However, This is the output that I get:
Array [
Object {
"amount": "5.00",
"date": "",
},
Object {
"amount": "5.00",
"date": "17/11/2020 22:26:16",
},
Object {
"0": "1",
"1": "7",
"10": " ",
"11": "2",
"12": "2",
"13": ":",
"14": "2",
"15": "6",
"16": ":",
"17": "1",
"18": "7",
"2": "/",
"3": "1",
"4": "1",
"5": "/",
"6": "2",
"7": "0",
"8": "2",
"9": "0",
"amount": "5.00",
"date": "17/11/2020 22:26:17",
},
]
How can I change the code bellow to output the correct array?
const [varAmount, setVarAmount] = useState(amount);
const [varTimeAndDateArray, setVarTimeAndDateArray] = useState([]);
const [varTimeAndDate, setVarTimeAndDate] = useState("");
const [varRecord, setVarRecord] = useState({
amount: "",
date: "",
});
function timeAndDate() {
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
setVarTimeAndDate(
date + "/" + month + "/" + year + " " + hours + ":" + min + ":" + sec
);
//Set an object to store a cost and the current time
setVarRecord({
...(varRecord.amount = varAmount),
});
setVarRecord({
...(varRecord.date = varTimeAndDate),
});
//Add the object (containing the cost and current time to an Array)
setVarTimeAndDateArray((varTimeAndDateArray) => [
...varTimeAndDateArray,
varRecord,
]);
}
<Button>
timeAndDate()
console.log(varTimeAndDateArray)
</Button>