Goal
I want to display a message based on whether the user is online or offline.
Summary of the Problem
- Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.
- Problem is mainly caused by a
setInterval()which calls a function every 6 second that changes the state (created usinguseStatehook)
Expected Result:
A function is called with a set interval that checks whether a user is online or offline and then displays a message if a user is offline
What I have tried:
export default function CardContainer() {
const [isOnline, set_isOnline] = useState(true);
function InternetErrMessagenger() {
if (navigator.onLine===true) set_isOnline(true);
if (navigator.onLine===false) set_isOnline(false);
}
setInterval(InternetErrMessagenger(), 6000);
return (
// the <InternetChecker /> component contains a message that gets displayed when offline
{isOnline !== true ? <InternetChecker /> : ""}
)
A Glimpse of my effort:
NOTE: I was thinking of using the
useEffecthook to solve this problem but could not make out how to do so. If you are thinking of any other way of addressing this problem, please share with me.
