Skip to content
Advertisement

push() removing previous values

I’m trying to push new values to an array but all I’m getting is only the last value computed. I’ve looked at other answers but couldn’t seem to figure it out. I appreciate the help thanks.

brief: upon clicking start I set a new date, then upon each time I click on the square div, the time is calculated between the previous date and the current date and the difference (diff) is oputput. I am attempting to save all the diff values into an array called diffArray using push() but only the last value is being saved/ output.

function App() {
  const [startTime, setStartTime] = useState();
  const [diff, setDiff] = useState();
  const [gate, setGate] = useState(false);
  const [left, setLeft] = useState(Math.floor(Math.random() * 1000));
  const [top, setTop] = useState(Math.floor(Math.random() * 1000));
  let diffArray = [];

  const divStyle = {
    height: 20,
    width: 20,
    top: top,
    left: left,
    position: "absolute",
    backgroundColor: "brown"
  };
  

  const handleClick = () => {
    
    setDiff((Date.now() - startTime) + '/ms');
    if (diff !== undefined) {
    diffArray.push(diff);
  
  }
    
    setStartTime(Date.now());
    respawn();
    ArrayMsOutput(diffArray);
  }

  const startClick = () => {
    setGate(!gate);
    setStartTime(Date.now());
  }

  const respawn = (e) => {
    
    setLeft(Math.floor(Math.random() * 1000));
    setTop(Math.floor(Math.random() * 900));
    
  }

  const ArrayMsOutput = (e) => {
    return e;
  }

  return (
    <div className="App">
      <button onClick={startClick}>{gate ? 'Stop' : 'Start'}</button>
      <div>{gate && diff}</div>
      <div>{ArrayMsOutput()}</div>
      {gate && <div onClick={handleClick} style={divStyle}>
      </div>}
    </div>
  );
}

export default App;

Advertisement

Answer

const handleClick = () => {

setDiff((Date.now() - startTime) + '/ms');
if (diff !== undefined) {
  diffArray.push(diff);
 }
}

This won’t work because your hook will have the value after the end of the function. You need to do:

const handleClick = () => {
    const newDiff = (Date.now() - startTime) + '/ms';

    setDiff(newDiff);
    if (newDiff !== undefined) {
      diffArray.push(newDiff);
    }
  }

Then, your array has only the latest value because you need to convert it to a useState hook: const [diffArray, setDiffArray] = useState([]) .

When you’ve done it, refacto your function to:

const handleClick = () => {
    const newDiff = (Date.now() - startTime) + '/ms';

    setDiff(newDiff);
    if (newDiff !== undefined) {
      setDiffArray(oldArray => [...oldArray, newDiff])
    }
  }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement