0

I want to add data in set state (setArraytime) but array data value is not reflecting in setstate.

const [vehicle_type, setVehicleType] = useState("");
      const [endTime, setEndtime] = useState("");
      const [startTime, setStartTime] = useState("");
    
      const [array_time, SetArrayTime] = useState([]);

 let value = {
    interval: vehicle_type,
    startTime: startTime,
    endTime: endTime,
  };

const doArrayChunks = () => {
   

    var inputDataFormat = "HH:mm a";
    var outputFormat = "HH:mm a";
    var tmp = moment(vehicle_type, inputDataFormat);
    var dif = tmp - moment().startOf("day");

    var startIntervalTime = moment(startTime, inputDataFormat).add(-dif, "ms");
    var endIntervalTime = moment(startTime, inputDataFormat);
    var finishTime = moment(endTime, inputDataFormat);

   

    var intervals = [];
    while (startIntervalTime < finishTime) {
      var format =
        startIntervalTime.format(outputFormat) +
        " - " +
        endIntervalTime.format(outputFormat);
      intervals.push(format);
      startIntervalTime.add(dif, "ms");
      endIntervalTime.add(dif, "ms");
      console.log("Intervals", intervals);
      SetArrayTime(intervals);
      console.log("array_time", array_time);
    }
  };

Tomas Vancoillie
  • 3,463
  • 2
  • 29
  • 45

3 Answers3

1

From looking at the code I can see that you want to replace the previous value of the array_time with the interval array. You can do it by using the below syntax

 SetArrayTime(prev_array_time => {
 let newArray = [...prev_array_time]
 newArray.push(intervals)
 return newArray
});

This should do the job.

State updates might be asynchronous

The above thread will help you understand whats happening in the background

jesvin palatty
  • 304
  • 2
  • 9
0

I would recommend trying to expose the previous array within the update function like so:

SetArrayTime(existingArray => [...existingArray, ...intervals])
Thomas Neil
  • 51
  • 1
  • 7
0

React changes the value of state when the callstack is empty.

As mentioned in the React documentation, there is no guarantee of setState being fired synchronously, so your console.log may return the state prior to it updating.

You can wait until the call stack is empty if you want to write out with

setTimeout(callback, 0)

https://developer.mozilla.org/en-US/docs/Glossary/Call_stack

szgezu
  • 68
  • 4