0

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>
John
  • 1
  • 1
  • don't think this was a duplicate https://snack.expo.io/OK_5ME5RE here is what you want – anthony willis muñoz Nov 17 '20 at 23:43
  • React state updates are asynchronous, so you can't log the *next* state just after enqueueing the update. Also, `timeAndDate` appears to be invoked in your render function, with an additional side-effect of the console log. You shouldn't update state or issue other side-effects in the render. – Drew Reese Nov 17 '20 at 23:45
  • @anthonywillismuñoz Thank you, that was an amazing help. You simplified that much better than I had it – John Nov 18 '20 at 00:47

0 Answers0