Home > Software design >  React - Query Parameters Are Empty on Page Load
React - Query Parameters Are Empty on Page Load

Time:06-05

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!

CodePudding user response:

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]);
  • Related