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

235
Visualizações
history.push does not re-render/refresh component in React/Typescript

I am navigating to a component that has ajax request, however the ajax call is only called on the first time the component is navigated to. All other routes look ok but this is the route with the problem:

    const history = useHistory();

    onClick={() => history.push(`/details/${id}`}

Routes:

import React from 'react';
import { BrowserRouter, Route, Switch} from 'react-router-dom';
import { QueryClient, QueryClientProvider } from 'react-query';
import { RouteComponentProps } from "react-router-dom";
import Component1 from '../Component1';
import Component2 from '../Component2';


const queryClient = new QueryClient()

const Routing: React.FunctionComponent = () => {

  return (
    <QueryClientProvider client={queryClient}>
    <BrowserRouter>
        <Switch>
          <Route exact path="/" component={Component1} />
          <Route path="/details/:id" render={(props: RouteComponentProps<any>) => <Component2 {...props}/>} />

          <Route component={NotFound} />
        </Switch>
    </BrowserRouter>
    </QueryClientProvider>
  )
}

export default Routing;

Component 2 code:

import React from 'react';
import { RouteComponentProps, useLocation } from "react-router-dom";
import { useQuery, useQueryClient} from 'react-query';


const Component2: React.FunctionComponent<RouteComponentProps<any>> = (props) => {

    const { state } = useLocation<stateType>();
    let id = props.match.params.id;

    const fetchData = async () => {
    const res = await fetch(`/detail/${id}`);
    return res.json();
    };

    const { data, status } = useQuery('chartInfo', fetchData, {
    staleTime: 5000,
    });

    return (
     {status === 'error' && (
                        <div className="mt-5">Error fetching data!</div>
                    )}
                    {status === 'loading' && (
                        <div className="mt-5">Loading data ...
                        </div>
                    )}
                    {status === 'success' && (
                        <div className="mt-5">
                      // data binded here
                        </div>
                    )}
    )

}

export default Component2;
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Now it's more clear what could cause the problem: looks like you are trying to fetch json from the same path, where you return the actual page. In other words you have to decide what do you expect from server when you request /detail/${id}: a page or a json. If server is already set up to return json, then you have to assign a different path for the page. But I would change the path to json to something like /api/detail/${id} instead, because normally people make /api/* routes for requesting json data

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