Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useHistory not defined in react custom Hook

I want to have a AI Voice assistant Alan AI to be integrated in my react app
So basically want to redirect pages using voice command.

But the problem is that, I want to use useHistory hook's push method to change pages, but whenever I access the variable it is undefined, I do not want to use window.location.href as it refreshes the app every time,

Can anyone suggest me where I am wrong usnig this hook/ or any other alternatives

import { useCallback, useEffect, useState } from "react";
import { useHistory } from "react-router-dom";

import { useCartContext } from "../context/cart_context";
import { useThemeContext } from "../context/theme_context";

import alanBtn from "@alan-ai/alan-sdk-web";

const COMMANDS = {
  OPEN_CART: "open-cart",
  TOGGLE_THEME: "toggle-theme",
};

const useAlan = () => {
  let history = useHistory();
  const { theme, toggleTheme } = useThemeContext();
  const { cart } = useCartContext();

  const [alanInstance, setAlanInstance] = useState(null);

  const openCart = useCallback(() => {
    if (cart.length < 1) {
      alanInstance.playText("cart is empty");
      return;
    }
    alanInstance.playText("opening cart");

    history.push("/cart");
    // window.location.href = "/cart";
  }, [alanInstance]);

  const changeTheme = useCallback(() => {
    alanInstance.playText("changing theme");
    toggleTheme();
  });

  useEffect(() => {
    window.addEventListener(COMMANDS.OPEN_CART, openCart);
    window.addEventListener(COMMANDS.TOGGLE_THEME, changeTheme);
    return () => {
      window.removeEventListener(COMMANDS.OPEN_CART, openCart);
      window.removeEventListener(COMMANDS.TOGGLE_THEME, changeTheme);
    };
  }, [openCart, changeTheme]);

  useEffect(() => {
    // history.push("/cart");
    // this also gives same error

    if (alanInstance != null) return;
    setAlanInstance(
      alanBtn({
        key: process.env.REACT_APP_ALAN_KEY,
        onCommand: ({ command }) => {
          window.dispatchEvent(new CustomEvent(command));
        },
      })
    );
  }, []);
  return null;
};

export default useAlan;

Every thing work's fine, voice is detected and the openCart function is ran, it's just that history is undefined

Error:

TypeError: Cannot read property 'push' of undefined
(anonymous function)
C:/Users/Sachin Verma/Desktop/Web Dev/React-E-Commerce-v2/src/hooks/useAlan.js:28
  25 |    }
  26 |    alanInstance.playText("opening cart");
  27 | 
> 28 |    history.push("/cart");
     | ^  29 |    // window.location.href = "/cart";
  30 |  }, [alanInstance]);
  31 | 

App.js code:

import React, { useState, useEffect } from "react";
import { BrowserRouter as Router, Switch, Route } from "react-router-dom";

import { useThemeContext } from "./context/theme_context";
import useAlan from "./hooks/useAlan";

import { Navbar, Sidebar, Footer } from "./components";
import {
  Home,
  SingleProduct,
  Cart,
  Checkout,
  Error,
  About,
  Products,
  PrivateRoute,
  AuthWrapper,
  Scan,
  History,
  ItemList,
} from "./pages";

function App() {
  const { theme } = useThemeContext();

  useAlan();

  useEffect(() => {
    if (theme === "dark-theme") {
      // set dark mode theme
      document.documentElement.className = "dark-theme";
    } else {
      // remove dark mode
      document.documentElement.className = "light-theme";
    }
  }, [theme]);

  return (
    <AuthWrapper>
      <Router>
        <Navbar />
        <Sidebar />

        <Switch>
          <Route exact path="/">
            <Home />
          </Route>

          <Route exact path="/about">
            <About />
          </Route>

          <Route exact path="/cart">
            <Cart />
          </Route>

          <Route exact path="/products">
            <Products />
          </Route>

          <PrivateRoute exact path="/history">
            <History />
          </PrivateRoute>

          <PrivateRoute exact path="/scan">
            <Scan />
            <ItemList />
          </PrivateRoute>

          <Route exact path="/products/:id" children={<SingleProduct />} />

          <PrivateRoute exact path="/checkout">
            <Checkout />
          </PrivateRoute>

          <Route path="*">
            <Error />
          </Route>
        </Switch>
        <Footer />
      </Router>
    </AuthWrapper>
  );
}

export default App;
like image 967
sachuverma Avatar asked Mar 01 '23 17:03

sachuverma


2 Answers

This happens when you are not properly nesting your application inside a valid Router which provides context for the history object. Make sure your top-level code is put inside a proper Router object context:

import { BrowserRouter } from "react-router-dom";

function App() {
    return (
        <BrowserRouter>
            ...(components that use react-router-hooks)
        </BrowserRouter>
    );
}

Same goes for React-Native: NativeRouter.

like image 133
zhulien Avatar answered Mar 05 '23 18:03

zhulien


useHistory has changed in v6, useHistory is now useNavigate and we can use it as follows:

instead of:

const history = useHistory()
history.push('/')

we now use:

const navigate = useNavigate()
naviaget('/')
like image 40
HibaHasan Avatar answered Mar 05 '23 18:03

HibaHasan