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

385
Visualizações
React - Query Parameters Are Empty on Page Load

I'm having an issue with navigation logic in React, and it'd be amazing to get some help.

I have front-end web app written in TypeScript, React and Ionic Framework V5.

The app has a fairly standard search box that redirects to a results page with the location /search?query={query here}.

When I hit the search button, the navigation is handled by React Router. I am redirected to the results page & the search query appears in the browser's address bar, but the query string is empty when it is fetched in the functional component logic - giving me incorrect search results.

The search box routes to the results page like so:

<IonButton fill="clear" className="search-button" routerLink={`/search?query=${searchValue}`}>
  <IonIcon name="search-outline" />
</IonButton>
  • Note that the routerLink property is simply an Ionic helper for React Router, the problem is the same if I encapsulate the button in a normal <Link/> tag.

On the search page, the query string is read like so:

const Home: React.FC<SimplePageProps> = ({ axios }) => {
  const queryParams = useQuery();
  const param = queryParams.get('query');

  const [products, setProducts] = useState([]);

  useEffect(() => {
    axios.get(`/products?query=${param}`)
      .then((response) => {
        const data = camelcaseKeys(response.data, { deep: true });
        setProducts(data.items.map((product: Product) => (
          <IonCol key={product.id} size-md="4" size-xl="3">
            <ProductCard product={product} />
          </IonCol>
        )));
      })
      .catch((error) => {
        // TODO show error element
        console.error(error);
      });
  }, [axios, param]);

As mentioned, the query string is empty when it is fetched in the functional component logic - giving me incorrect search results. When I refresh the page, the query string is not empty and the search results appear. Any ideas?

Thanks so much in advance!

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

0

After sleeping on it & some more searching, I managed to fix this.

My solution was to strip things back to a vanilla JavaScript command, window.location.search. This always fetches the correct query parameters from the URL, whereas the React Router helper hooks would be undefined when first routed to the page.

useLocation() is included so that when another search is performed from the results page, the React component re-renders to reflect the new query string.

const Home: React.FC<SimplePageProps> = ({ axios }) => {
  // parse query string parameter
  const { search } = window.location;
  const query = new URLSearchParams(search).get('query');

  useLocation(); // including this forces a re-render when the URL changes

  const [products, setProducts] = useState([]);

  useEffect(() => {
    axios.get(`/products?query=${query}`)
      .then((response) => {
        const data = camelcaseKeys(response.data, { deep: true });
        setProducts(data.items.map((product: Product) => (
          <IonCol key={product.id} size-md="4" size-xl="3">
            <ProductCard product={product} />
          </IonCol>
        )));
      })
      .catch((error) => {
        // TODO show error element
        console.error(error);
      });
  }, [axios, query]);
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