Open a modal when connection is lost

Viewed 25

I am using antdesign, I am trying to open the modal whenever the connection is down. I used a useEffect and a local state just like for a regular modal but it does not seem to work

import React, { useState, useEffect } from 'react';
import 'antd/dist/antd.css';
import './index.css';
import { Modal } from 'antd';


const App = () => {
  const [isModalOpen, setIsModalOpen] = useState(false);
const online=Navigator.onLine


useEffect((online) => {
  if (!online) {
    setIsModalOpen(true);
  }
}, [online]);

  return (
    <>
    
      <Modal title="Basic Modal" open={isModalOpen} >
        <p>Some contents...</p>
        <p>Some contents...</p>
        <p>Some contents...</p>
      </Modal>
    </>
  );
};

export default App;
1 Answers

The value of online doesn't change since you're assigning the value on initialisation. Instead, set up the online and offline event listeners in your useEffect hook instead:

useEffect(() => {
  const connectionStatusChange = () => {
    setIsModalOpen(!Navigator.onLine);
  }

  window.addEventListener('online', connectionStatusChange);
  window.addEventListener('offline', connectionStatusChange);

  return () => {
    window.removeEventListener('online', connectionStatusChange);
    window.removeEventListener('offline', connectionStatusChange);
  };
});
Related