Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

256
Visualizações
How to check online status in React.js?

I have created a function that checks if the application is online or not. However, based on the MDN documentation, navigator.onLine is giving false positives on Chrome and Safari which I'm currently experiencing right now. Is there any other way to resolve this current issue?

useOnlineStatus.ts:

import { useEffect, useState } from 'react'

const getOnlineStatus = (): boolean => {
  return typeof navigator !== 'undefined' &&
    typeof navigator.onLine === 'boolean'
    ? navigator.onLine
    : true
}

const useOnlineStatus = (): boolean => {
  const [onlineStatus, setOnlineStatus] = useState(getOnlineStatus())

  const goOnline = () => setOnlineStatus(true)

  const goOffline = () => setOnlineStatus(false)

  useEffect(() => {
    window.addEventListener('online', goOnline)
    window.addEventListener('offline', goOffline)

    return () => {
      window.removeEventListener('online', goOnline)
      window.removeEventListener('offline', goOffline)
    }
  }, [])

  return onlineStatus
}

export default useOnlineStatus

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

One way you could try is to send a request to your own origin to check whether your application is online or not.

The query params (q) is randomised to avoid cached responses.

const isAppOnline = async() => {
  if (!window.navigator.onLine) return false

  const url = new URL(window.location.origin)
  url.searchParams.set('q', new Date().toString())

  try {
    const response = await fetch(
      url.toString(),
      { method: 'HEAD' },
    )

    return response.ok
  } catch {
    return false
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda