Gunsela
Gunsela

Reputation: 470

React hooks : 'Cannot read property 'push' of undefined'

I'm trying to redirect my homepage to "/call" page based on a redux state. I can go to that component by typing the url manually but cant do it with a function. I tried "Redirect to", "history.push" but none of them worked for me. I cant solve the problem. Here is my code;

const Phone = ({ hidden, photoOpened, inCall }) => {
  const dispatch = useDispatch(getContacts());
  let history = useHistory();

  useEffect(() => {
    if (inCall.inCall) {
      history.push('/call')
    }
  }, [inCall]);

  useEffect(() => {
    dispatch(getContacts());
  }, [])

  return (
    <div hidden={process.env.NODE_ENV === 'development' ? !hidden : hidden} className={photoOpened ? "phone-container-rotate" : "phone-container"}>
      <div className="coque" />
      <Suspense fallback={<div className="animated fadeIn pt-1 text-center">Loading...</div>}>
        <HashRouter basename="/phone">
          <div
            className="phone-content"
            style={{ backgroundImage: `url(${background})` }}
          >
            <HeaderBar />
            <BannerNotifications />
            <Switch>
              {routes.map((route, idx) => {
                return route.component ? (
                  <Route
                    key={idx}
                    path={route.path}
                    exact={route.exact}
                    render={props => <route.component {...props} />}
                  />
                ) : null;
              })}
            </Switch>
          </div>
          <Route component={BottomPhoneNavigator} />
        </HashRouter>
      </Suspense>
    </div>
  );
};

Upvotes: 1

Views: 253

Answers (2)

You could try and test for history existence of the history in your effect, also add it to dependency list

  useEffect(() => {
    if (history && inCall.inCall) {
      history.push('/call')
    }
  }, [inCall, history]);

And important thing, your component using this hook must be within the Router, I see you'\re using HashRouter but as child of component using the hook.

Also if you're stuck to this structure, why wont you try to use Redirect within the Switch? This could work with some smart test so you wont end up in a loop:)

Upvotes: 3

Alyks
Alyks

Reputation: 41

To use history your Phone component should be inside router component

Upvotes: 1

Related Questions