Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3428 | Rev 3585 | Ir a la última revisión | Autoría | Comparar con el anterior | Ultima modificación | Ver Log |

import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'

import { axios } from './utils'
import { useFetch } from '@hooks'
import { labelsAdapter } from './utils/labels'
import { setIntlLabels } from './redux/intl/intl.action'
import { setCrendentials } from './redux/auth/auth.actions'

import AppRoutes from './routes/routes'
import ErrorPage from './pages/error/error-page'
import Spinner from './components/UI/Spinner'

import './styles/globals.scss'

export default function App() {
  const [loading, setLoading] = useState(true)
  const [credentialsError, setCredentialsError] = useState(false)
  const { data: labels } = useFetch('/language')
  const { is_logged_in } = useSelector((state) => state.auth)
  const dispatch = useDispatch()

  const getCredentials = async () => {
    const response = await axios.get('/signin')
    const { data, success } = response.data
    if (!success) throw new Error('Error al obtener las credenciales')
    return data
  }

  useEffect(() => {
    setLoading(true)

    getCredentials()
      .then((credentials) => {
        window.localStorage.setItem('jwt', credentials.jwt)
        dispatch(setCrendentials(credentials))
      })
      .catch((error) => {
        console.error(error.message)
        setCredentialsError(true)
      })
      .finally(() => setLoading(false))
  }, [is_logged_in])

  useEffect(() => {
    dispatch(setIntlLabels(labelsAdapter(labels)))
  }, [labels])

  if (loading) {
    return <Spinner />
  }

  if (credentialsError) {
    return <ErrorPage />
  }

  return <AppRoutes />
}