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

205
Visualizações
Differentiate between 404 error and is loading in react and render the components base on that. React

I am trying to render a skeleton component on loading of the data or 404 error component if data not found so far i have tried using if else statements and logical operators so far none work properly.

const [post, setPost] = useState(null);
const [postExternal, setPostExternal] = useState([]);

const fetchPost = () => {
  axios.get(`${API_ONE}/posts?id=${id}`).then((response) => {
    setPost(response.data);
  });
  axios.get(`${API_TWO}/posts?id=${id}`).then((response) => {
    setPostExternal(response.data);
  });
  return;
};

const location = useLocation();
const id = location.pathname.split('/')[2];

useEffect(() => {
  fetchPost();
}, [id]);

{
  post && postExternal && (
    <div>
      <h1>{post.title}</h1>
      <img src={postExternal} />
    </div>
  );
}
{
  !post &&
    (post && post.id === postExternal.id ? (
      <NotFound message='not found' />
    ) : (
      <SkeletonItemPage />
    ));
}

Note: The data is fetched from two different apis

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

0

Define a loading state variable as the follow:

const [isLoading, setIsLoading] = useState(false);

Then your fetchPosts function would be like:

  const fetchPost = () => {
            const apiOnePromise = axios.get(`${API_ONE}/posts?id=${id}`);
            const apiTwoPromise = axios.get(`${API_TWO}/posts?id=${id}`);
            //toggle loader
            setLoading(true);
            Promise.all([apiOnePromise, apiTwoPromise])
                .then(values => {
                    //handle your responses here
                })
                .finally(() => {
                    //toggle loader again
                    setLoading(false);
                })
        };
 

Using this loading variable you can differentiate between the statues, so with your jsx you can do:

   { loading && <SkeletonItemPage /> }
   { !loading && posts.length === 0 && <NotFound message='not found' />  }
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