1

I have an issue while creating simple HOC which should redirect to 404 when there are no query params. Otherwise, it should just return a component.

import React, { useState, useEffect } from 'react';
import { Redirect } from 'react-router-dom';

import { api } from '../utils/api';

export default (WrappedComponent, queryParamKey) => {
   return () => {
   const [ paramAvailability, setParamAvailability ] = useState(false);

  useEffect(() => {
    const urlParams = new URLSearchParams(document.location.search);
    const token = urlParams.get(queryParamKey);

    setParamAvailability(!!token);
  });

  return paramAvailability ? (
    <WrappedComponent {...this.props} />
  ) : <Redirect to="/404" />;
  };
};

So every time I'm wrapping a component it redirect to 404 either there are or there are not query params available.

Murakami
  • 3,474
  • 7
  • 35
  • 89
  • That's weird... That seems to be [exactly how `Redirect` is supposed to be used](https://stackoverflow.com/questions/43230194/how-to-use-redirect-in-the-new-react-router-dom-of-reactjs) – Nino Filiu Mar 20 '19 at 21:38
  • What error are you getting? What is not working as expected? – ManavM Mar 20 '19 at 21:43
  • As stated above, there is no error, it just redirects every time even though there are params available in URL – Murakami Mar 20 '19 at 21:44

1 Answers1

2

paramAvailability is false by default. useEffect is first called after initial render. So you always Redirect.

To fix your HOC just extract checking logic to a separate function and use it to set the default state:

export default (WrappedComponent, queryParamKey) => {
   return props => {

    function checkParam() {
        const urlParams = new URLSearchParams(document.location.search);
        const token = urlParams.get(queryParamKey);
        return !!token;
    }

   const [ paramAvailability, setParamAvailability ] = useState(checkParam());


  useEffect(() => {
    setParamAvailability(checkParam());
  });

  return paramAvailability ? (
    <WrappedComponent {...props} />
  ) : <Redirect to="/404" />;
  };
};
Murakami
  • 3,474
  • 7
  • 35
  • 89
UjinT34
  • 4,784
  • 1
  • 12
  • 26