0

UseHistory Hook while trying to push to another page says undefined while trying to programmatically navigate after the async function

Context

import React, { createContext, useContext, useReducer, useState } from "react";
import AuthReducer from "./reducers/AuthReducer";
import axios from "axios";
import { UserState } from "./types";
import { useHistory } from "react-router-dom";
import { Plugins } from "@capacitor/core";
import { NavContext } from "@ionic/react";

// Initial State
const initialState: UserState = {
  user: {},
  error: null,
  loading: true,
  location: {},
  getLocation: () => {},
  UserLogin: () => {},
  UserRegister: () => {},
};

// Create Context
export const AuthContext = createContext<UserState>(initialState);

// Provider
export const AuthProvider: React.FC = ({ children }) => {
  const URL = "https://backend.com/api/v1/auth";
  const [state, dispatch] = useReducer(AuthReducer, initialState);
  const [location, setLocation] = useState<object>({ long: "", lat: "" });
  const [user, setUser] = useState();
  const { Toast, Geolocation } = Plugins;
  const { navigate } = useContext(NavContext);
  const history = useHistory();

  // Get Location
  const getLocation = async () => {
    try {
      const coordinates = await Geolocation.getCurrentPosition();
      const lat = coordinates.coords.latitude;
      const long = coordinates.coords.longitude;
      setLocation({
        long,
        lat,
      });
      console.log(location);
    } catch (error) {
      console.log(error);
    }
  };

  getLocation();

  // Login
  const UserLogin = async (user: any) => {
    try {
      const res: any = await axios.post(`${URL}/login`, user, {
        headers: { "Content-Type": "application/json" },
      });
      dispatch({
        type: "LOGIN",
        user: res.data,
      });
      console.log(res.data);
      await Toast.show({
        text: "Login successfully",
        duration: "short",
        position: "bottom",
      });
      setUser(res.data);
      alert("Done");
      history.push("/dashboard/Home");
      // navigate("/dashboard/", "forward", "push");
    } catch (error) {
      dispatch({
        type: "USER_ERROR",
        payload: error.message,
      });
      console.log(error.message);
      await Toast.show({
        text: `${error.message}`,
        duration: "short",
        position: "bottom",
      });
    }
  };

  // Register
  const UserRegister = async (user: any) => {
    try {
      const res = await axios.post(`${URL}/signup`, user, {
        headers: { "Content-Type": "application/json" },
      });
      dispatch({
        type: "REGISTER",
        user: res.data,
      });
      console.log(res.data);
      await Toast.show({
        text: "Account created successfully",
        duration: "short",
        position: "bottom",
      });
      alert("Done");
      history.push("/login");
    } catch (error) {
      dispatch({
        type: "USER_ERROR",
        payload: error.message,
      });
      console.log(error.message);
      await Toast.show({
        text: `${error.message}`,
        duration: "short",
        position: "bottom",
      });
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user: state.user,
        loading: state.loading,
        error: state.error,
        location,
        getLocation,
        UserLogin,
        UserRegister,
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

Please I think I'm missing something... I want to navigate programmatically to my dashboard after the Login & signup Action. Even if i try to use the NavContext

1 Answers1

-1

You need to wrap your component in withRouter()

export default withRouter(AuthProvider)

Do not forget to import it first:

import { useHistory, withRouter } from "react-router-dom";
Moatezz
  • 1
  • 2