I want to check if user is online in a React app?

Viewed 2868

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 using useState hook)

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:

enter image description here

NOTE: I was thinking of using the useEffect hook 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.

2 Answers

You could do like this

  1. useEffect will initiate the setInterval on component mount return function of the useEffect remove the interval event after comopnent unmount

Codesanbox Demo

export default function CardContainer() {
 const [isOnline, set_isOnline] = useState(true);
 let interval = null;

 const InternetErrMessagenger = () => set_isOnline(navigator.onLine===true); // for do like this shortform

 
 useEffect(()=>{
    interval = setInterval(InternetErrMessagenger, 6000); // call the function name only not with function with call `()`
    return ()=>{
       clearInterval(interval) // for component unmount stop the interval
    }
 },[])
 
 return (
    // the <InternetChecker /> component contains a message that gets displayed when offline
    {isOnline !== true ? <InternetChecker /> : ""}
 )
Related