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

169
Visualizações
Render component from a non react component

I am trying to render component from a javascript function

export const fetcher = (signal, method, route, content = null) => {
    

    return fetch(`${API_URL}${route}`, options)
        .then(res => {
            if (res.status === 401 && isLoggedIn())
                // SHOW SNACKBAR HERE
                return Promise.reject("INVALID_TOKEN");

            if (res.status === 500)
                // SHOW SNACKBAR HERE
                return Promise.reject("UNKNOWN_ERROR");

            if ((res.status < 200 || res.status >= 300) && res.status !== 401)
                // SHOW SNACKBAR HERE
                return Promise.reject("UNKNOWN_ERROR");

            if(res.status === 204)
                // SHOW SNACKBAR HERE
                return res.status;

            if (res.headers.get("Content-Type").indexOf("application/json") !== -1)
                // SHOW SNACKBAR HERE
                return res.json();

            return res.status === 200 ? res.text() : res.status;
        })
        .catch(err => {
            console.log(err, `${method?.toUpperCase()} ${route}`);

            if (err === "INVALID_TOKEN") {
                removeToken();
                window.location = "/";
            }
            else if (err === "UNKNOWN_ERROR") {
                window.location = "/500";
            }
            else if (err.name !== 'AbortError') {
                window.location = '/networkerror';
            }

            return Promise.reject();
        });
};

I tried to use HOC but this is not worked for me.

Is it possible to render react elements outside react context ?

Thank you !

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

0

Not sure this is possible, at least not in a graceful matter.

What we usually do when fetching, is handle the related events in the component that calls the fetch function.
You can have an error state that you set accordingly to whether the function ends up in the catch block. And then you can conditionally call the needed component from the render.

So for example, something like this:

import { fetchData } from ...

export function Foo() {
   const [error, setError] = useState(null);

   async const onFetch = () => {
      try {
         ...
         await fetch();
      } catch (error) {
         setError(error);
      }
   }
   
   useEffect(() => {
      // Initial -
      onFetch();
   }, []);

   return (
      ...
      {error !== null && <SnackbarComp error={error} />}
   )
}

I know this doens't necessarily answer your question.
Feel free to disregard if not helpful.

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