cant append array(state element) with setinterval() in react - javascript

const [timer,setTimer] = useState()
const [number, setNumber] = useState()
const [list, setlist] = useState([])
const numberChange = (number)=>{
setNumber(number)
if (!(list.find(item=>item===number))){
setlist([...list,number])}
}
const randomNumber=()=> 1+Math.floor(Math.random()*90)
const randNumberChange=()=>{
let randNumber = randomNumber()
if (list.find(item=>item===randNumber))
randNumberChange()
else
numberChange(randNumber)
}
const startTimer = () => {
setTimer(setInterval(()=>{
randNumberChange()
}, 5000))
}
const stopTimer=()=>{
clearInterval(timer)
}
The list is always rendering only one item and not appending it.
When randNumberChange is called separately then the list gets appended but not with setInterval.
When startTimer funcion is executed is stopped with stopTimer and then started again it appends second item then stop and it repeats

Change setlist([...list,number])} to setlist((prevState) => [...prevState, number]). React set state is async in nature. So to get the correct list value from the state you would need to get the value from previous state. Doc
Suggestion: that instead of setting timer in state, you can start the interval in useEffect.
Also in numberChange function, you should get the list from previous state and then append the new number in that. This will make sure that the list value is updated before adding new number.
import React, { Component, useState } from "react";
import { render } from "react-dom";
import Hello from "./Hello";
import "./style.css";
const Test = () => {
const [number, setNumber] = useState(null);
const [list, setlist] = useState([]);
const numberChange = number => {
setNumber(number);
if (!list.find(item => item === number)) {
setlist((prevState) => [...prevState, number]);// instead of directly using list value, get it from previous state
}
};
const randomNumber = () => 1 + Math.floor(Math.random() * 90);
const randNumberChange = () => {
console.log("here");
let randNumber = randomNumber();
if (list.find(item => item === randNumber)) randNumberChange();
else numberChange(randNumber);
};
const startTimer = () => {
return setInterval(() => { randNumberChange(); }, 5000);
}
const stopTimer = (timer) => {
clearInterval(timer)
}
React.useEffect(() => {
const timer = startTimer();
return ()=> stopTimer(timer);
}, []);
console.log(list);
return <div>{number}</div>;
};

You'll need to use useEffect hook:
useEffect(() => {
// You don't need timer state, we'll clear this later
const interval = setInterval(() => {
randNumberChange()
},5000)
return () => { // clear up
clearInterval(interval)
}
},[])

use useEffect with setTimeout it is work as setInterval
useEffect(() => {
setTimeout(() => setList([...list, newValue]), 2000)
}, [list])

Related

How to properly clear fetch timeout in React component?

I'm fetching Dogs from my API through a JavaScript timeout. It works fine, except it fails to clear the timeout sometimes:
import { useState, useEffect, useCallback } from 'react';
const DogsPage = () => {
const [dogs, setDogs] = useRef([]);
const timeoutId = useRef();
const fetchDogs = useCallback(
async () => {
const response = await fetch('/dogs');
const { dogs } = await response.json();
setDogs(dogs);
timeoutId.current = setTimeout(fetchDogs, 1000);
},
[]
);
useEffect(
() => {
fetchDogs();
return () => clearTimeout(timeoutId.current);
},
[fetchDogs]
);
return <b>Whatever</b>;
};
It looks like the problem is that sometimes I unmount first, while the code is still awaiting for the Dogs to be fetched. Is this a common issue and if so, how would I prevent this problem?
One idea would be to use additional useRef() to keep track of whether the component has been unmounted in between fetch:
const DogsPage = () => {
const isMounted = useRef(true);
const fetchDogs = useCallback(
async () => {
// My fetching code
if (isMounted.current) {
timeoutId.current = setTimeout(fetchDogs, 1000);
}
},
[]
);
useEffect(
() => {
return () => isMounted.current = false;
},
[]
);
// The rest of the code
};
But perhaps there is a cleaner way?
You can assign a sentinel value for timeoutId.current after clearing it, then check for that value before starting a new timer:
import { useState, useEffect, useCallback } from 'react';
const DogsPage = () => {
const [dogs, setDogs] = useRef([]);
const timeoutId = useRef();
const fetchDogs = useCallback(
async () => {
const response = await fetch('/dogs');
const { dogs } = await response.json();
setDogs(dogs);
if (timeoutId.current !== -1)
timeoutId.current = setTimeout(fetchDogs, 1000);
},
[]
);
useEffect(
() => {
fetchDogs();
return () => void (clearTimeout(timeoutId.current), timeoutId.current = -1);
},
[fetchDogs]
);
return <b>Whatever</b>;
};

clearInterval() doesn't clear interval in React

I want to increment the number of users after each 200ms till 5000 with the below code. But it doesn't clear the interval when the number of users greater than 5000.
const Cards = () => {
const [users, setUsers] = useState(40);
useEffect(() => {
const setIntervalUsers = setInterval(() => {
setUsers((prevUsers) => prevUsers = prevUsers + 100)
}, 200);
if (users >= 5000) {
console.log('ok');
clearInterval(setIntervalUsers)
}
}, []);
return (<div>number of users {users} </div>)}
I would suggest you to return a clean up function so you don't register the interval twice in case you are in StrictMode with React 18, and also to remove it from the memory when the component gets unmounted.
Also use a ref set with useRef and a separate useEffect that would watch changes in users and clear the interval there. Like so:
import { useEffect, useRef, useState } from "react";
const Cards = () => {
const [users, setUsers] = useState(40);
const intervalRef = useRef();
useEffect(() => {
if (users >= 5000) {
console.log("ok");
clearInterval(intervalRef.current);
}
}, [users]);
useEffect(() => {
intervalRef.current = setInterval(() => {
setUsers((prevUsers) => (prevUsers = prevUsers + 100));
}, 200);
return () => clearInterval(intervalRef.current);
}, []);
return <div>number of users {users} </div>;
};
This doesnt work because:
you never call the useEffect again to check if the condition is met
the interval ref is lost
I made a working sample of your code here : https://codepen.io/aSH-uncover/pen/wvmYdNy
Addintionnaly you should clean the interval when the component is destroyed by returning the cleanInterval call in the hook that created the inteerval
const Card = ({ step }) => {
const intervals = useRef({})
const [users, setUsers] = useState(40)
useEffect(() => {
intervals.users = setInterval(() => {
setUsers((prevUsers) => prevUsers = prevUsers + step)
}, 200)
return () => clearInterval(intervals.users)
}, [])
useEffect(() => {
if (users >= 5000) {
clearInterval(intervals.users)
}
}, [users])
return (<div>number of users {users} </div>)
}
I came up with this. You can try it out. Although there are many ways suggested above
const [users, setUsers] = useState(40);
const [max_user, setMaxUser] = useState(true);
let setIntervalUsers: any;
let sprevUsers = 0;
useEffect(() => {
if (max_user) {
setIntervalUsers = setInterval(() => {
sprevUsers += 100;
if (sprevUsers >= 5000) {
setMaxUser(false);
clearInterval(setIntervalUsers);
} else {
setUsers(sprevUsers);
}
}, 200);
}
}, []);
The way how you check for your condition users >= 5000 is not working because users is not listed as a dependency in your useEffect hook. Therefore the hook only runs once but doesnt run again when users change. Because of that you only check for 40 >= 5000 once at the beginning.
An easier way to handle that is without a setInterval way.
export const Cards = () => {
const [users, setUsers] = useState(40);
useEffect(() => {
// your break condition
if (users >= 5000) return;
const increment = async () => {
// your interval
await new Promise((resolve) => setTimeout(resolve, 200));
setUsers((prevState) => prevState + 100);
}
// call your callback
increment();
// make the function run when users change.
}, [users]);
return <p>current number of users {users}</p>
}

Set interval on component mount is getting too fast and is not spreading my array

Goal is to display a real time log that comes from an async function ( this func will return the last log ) and is updated each second. After that i want to accumulate the results on an array and if it get bigger than 5 i want to remove the first element.
Expected: A list of 5 items displayed on screen that is updated each second.
Results: Array is not accumulating above 2 items and the update is random and fast
code ->
const [logs, setLogs] = useState([])
const getLogs = async () => {
const lastLog = await window.getAppLogs()
if (logs.length > 5) {
// here i tried this methods ->
// reduceLogs.shift()
// reduceLogs.splice(0, 1)
const reduceLogs = [...logs, lastLog ]
delete reduceLogs[0]
return setLogs(reduceLogs)
}
const test = [...logs, lastLog] // this line is not accumulating above 2
setLogs(test)
}
useEffect(() => {
setInterval(getLogs, 1000);
}, [])
Updating state in setinterval needs to use the => syntax. So it should be -
setLogs(prevState => [...prevState.slice(-4), lastLog])
Plus you need to clear the interval as well. I've made a demo to display last 5 users when they are updated every second (from api).
export default function App() {
const [users, setUsers] = useState([
"michael",
"jack",
]);
const getUser = async () => {
const response = await fetch("https://randomuser.me/api/?results=1");
const user = await response.json();
return user;
};
const getUsers = async () => {
const user = await getUser();
setUsers(prevState => [...prevState.slice(-4), user.results[0].name.first]);
};
useEffect(() => {
const handle = setInterval(getUsers, 1000);
return () => {
clearInterval(handle);
};
}, []);
return (
<div className="App">
<h1>Hello CodeSandbox</h1>
{users.map((log) => (
<div>{log}</div>
))}
</div>
);
}
Update: This should be your getLogs function, no if check, no return etc.
const getLogs = async () => {
const lastLog = await window.getAppLogs()
setLogs((prevState) => [...prevState.slice(-4), lastLog]);
}
hey AG its almost working perfectly, updates are constant now and it is accumulating. But is still not reducing length of the array. Its like u show me:
const [logs, setLogs] = useState([])
const getLogs = async () => {
const lastLog = await window.getAppLogs()
if (logs.length > 4) {
return setLogs((prevState) => [...prevState.slice(-4), lastLog])
}
setLogs((prevState) => [...prevState, lastLog])
}
useEffect(() => {
const handle = setInterval(getLogs, 2500);
return () => {
clearInterval(handle);
};
}, [])

Updated state value is not reflected inside setInterval() in React

I have the following:
const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);
const startTimer = () => {
myTimer.current = setInterval(() => {
console.log(isPaused); // always says "false"
}, 1000);
};
Elsewhere in the code while this timer is running I'm updating the value of isPaused:
setIsPaused(true);
But this isn't reflected in the console log, it always logs false. Is there a fix to this?
The myTimer.current never changed which means isPaused is always false inside the function.
You need to make use of useEffect to update myTimer.current every time isPaused is updated.
useEffect(() => {
function startTimer() {
myTimer.current = setInterval(() => {
console.log(isPaused);
}, 1000);
};
startTimer();
return () => clearInterval(myTimer.current); // cleanup
}, [isPaused]);
You can do something like this,
const [isPaused, setIsPaused] = useState(false);
const myTimer = useRef(null);
const startTimer = () => {
myTimer.current = setInterval(() => {
console.log(isPaused); // now updates
}, 1000);
};
useEffect(() => {
startTimer();
return () => myTimer.current != null && clearInterval(myTimer.current);
}, [isPaused]);
return (
<div>
<b>isPaused: {isPaused ? "T" : "F"}</b>
<button onClick={() => setIsPaused(!isPaused)}>Toggle</button>
</div>
);
Use Others function
use useInterval from 30secondsofcode
const Timer = props => {
const [seconds, setSeconds] = React.useState(0);
useInterval(() => {
setSeconds(seconds + 1);
}, 1000);
return <p>{seconds}</p>;
};
ReactDOM.render(<Timer />, document.getElementById('root'));
Or, use react-useInterval package
function Counter() {
let [count, setCount] = useState(0);
const increaseCount = amount => {
setCount(count + amount);
};
useInterval(increaseCount, 1000, 5);
return <h1>{count}</h1>;
}

How to hold the value of a variable inside functional component

I have variable myinterval inside functional component with Hooks, and I update and asign new value this myinterval, just inside useEffect.
But after a state gets update myinterval holds the prev value, I mean the value which I initilized inside functional components.
function App(props) {
const [name, setName] = useState('Muhammad');
let myinterval = null;
useEffect(()=>{
myinterval = setInterval(()=> {}, 100);
}, []);
const print = async () => {
setName('new name');
console.log(myinterval);
};
return <button className="App" onClick={print}>hey</button>;
}
Now as you can see when I click print function, the first time it is not null, but in second time it is null.
This is because of setName('new name');, actually after setName('new name'); called, then myinterval return null value.
What I want?
I want myinterval variable should return always the value which re-initialized inside useEffect.
As per my need, I can't declare my myinterval variable outside of function App(props){}.
Here is an example I shown it very simple.
Simple Code Example
This will set the interval only on first render and cancel it on unmount
useEffect(()=>{
myInterval = setInterval(()=> {}, 100);
return () => clearInterval(myInterval)
}, []);
}
If you want to store a reference to the interval id, you should not use a plain variable (which is set at each render), but rather use a React ref with the useRef hook
function App(props) {
const [name, setName] = useState('Muhammad');
const myInterval = useRef(null)
useEffect(()=>{
myInterval.current = setInterval(()=> {}, 100);
return () => {
if (myInterval.current) {
clearInterval(myInterval.current)
myInterval.current = null
}
}
}, []);
const print = async () => {
setName('new name');
console.log(myInterval.current);
};
return <button className="App" onClick={print}>hey</button>;
}
let myinterval = null;
runs every time, on every render
useEffect(()=>{
myinterval = setInterval(()=> {}, 100);
}, []);
runs only at mount, leaving myinterval with a null value
Fix for what you want to achieve:
import React, { useState, useEffect, useMemo } from "react";
import ReactDOM from "react-dom";
import "./styles.css";
function App() {
const [name, setName] = useState("Muhammad");
const [timeout, setTimeout] = useState("init value");
useEffect(() => {
setInterval(() => setTimeout("new value"), 3000);
}, []);
const print = async () => {
setName("setting name");
console.log(timeout);
};
return (
<button className="App" onClick={print}>
hey
</button>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Categories