Answer the question
In order to leave comments, you need to log in
I have a React app (random number generator), why is the app not working properly?
Description:
Each time we click on "Add number", a random number is added to the end of the list.
"Start" - starts an interval of 1 second, which adds a random number to the end of the list.
"Stop" - stops the timer.
Help to find a bug and if you can modify the code
import React from "react";
import "./styles.css";
export default function App() {
let timer = null;
const [numbers, setNumbers] = React.useState([1, 2, 3]);
const addRandomNumber = () => {
const random = Math.round(Math.random() * 10);
setNumbers([...numbers, random]);
};
const start = () => {
timer = setInterval(addRandomNumber, 1000);
};
const stop = () => {
clearInterval(timer);
};
return (
<div className="App">
<ul>
{numbers.map(num => (
<li>{num}</li>
))}
</ul>
<div className="buttons">
<button onClick={() => addRandomNumber()}>Добавить число</button>
<button onClick={() => start()}>Старт</button>
<button onClick={() => stop()}>Стоп</button>
</div>
</div>
);
}
Answer the question
In order to leave comments, you need to log in
Lose the value that setInterval returns. We need another useState.
When updating numbers inside addRandomNumber , use the value it had when addRandomNumber was created. Instead of a new value, you can pass a state update function to a function - it receives the current value as an argument and must return a new one.
function App() {
const [ numbers, setNumbers ] = React.useState([ 1, 2, 3 ]);
const [ timerId, setTimerId ] = React.useState(null);
const add = () => setNumbers(numbers => [ ...numbers, Math.random() * 10 | 0 ]);
const start = () => setTimerId(setInterval(add, 1000));
const stop = () => (clearInterval(timerId), setTimerId(null));
return (
<div>
<ul>
{numbers.map(n => <li>{n}</li>)}
</ul>
<div>
<button onClick={add} disabled={timerId}>Добавить число</button>
<button onClick={start} disabled={timerId}>Старт</button>
<button onClick={stop} disabled={!timerId}>Стоп</button>
</div>
</div>
);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question