Proyectos de Subversion LeadersLinked - SPA

Rev

Rev 3681 | 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 { logout, setCrendentials } from './redux/auth/auth.actions';

import AppRoutes from './routes/routes';
import Spinner from './components/UI/Spinner';

export default function App() {
  const [loading, setLoading] = useState(true);
  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) => {
        if (error.message.includes('La sesión ha caducado')) window.localStorage.removeItem('jwt');
        dispatch(logout());
      })
      .finally(() => setLoading(false));
  }, [is_logged_in]);

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

  if (loading) {
    return <Spinner absolute />;
  }

  return <AppRoutes />;
}