phongyewtong
phongyewtong

Reputation: 5319

I am trying to history.push but its always undefined on react

I am trying to history.push but its always undefined.

import React, { useEffect, useState } from "react";
import * as Firebase from "firebase/app";
import "firebase/auth";
import DBAPI from "./database/database-api"
import DBName from "./database/database-name"
import { useHistory } from "react-router-dom";

export const UserContext = React.createContext();

export const UserProvider = ({ children }) => {
  const [currentUser, setCurrentUser] = useState(null);
  const [isAdmin, setIsAdmin] = useState(null);
  const [isVendor, setIsVendor] = useState(null);
  const [pending, setPending] = useState(true);

  let history = useHistory();

  useEffect(() => {
    Firebase.auth().onAuthStateChanged(async (user) => {
        if (user != null) {
            setCurrentUser(user)

            let response = await Promise.all([
              DBAPI.checkUserExist(DBName.admin, user.uid),
              DBAPI.checkUserExist(DBName.vendor, user.uid)
            ]);

            console.log(response[0].data)
            console.log(response[1].data)

            if (response[0].data) setIsAdmin(true)  // admin
            if (response[1].data) setIsVendor(true) // vendor

            history.push(`${process.env.PUBLIC_URL}/products`)
        } else {
            setIsVendor(false)
            setIsAdmin(false)
        }

        setPending(false)
    });
  }, []);

  if(pending){
    return <>Loading...</>
  }

  return (
    <UserContext.Provider
      value={{
        currentUser,
        isAdmin,
        isVendor
      }}
    >
      {children}
    </UserContext.Provider>
  );
};

Upvotes: 0

Views: 112

Answers (1)

Lhew
Lhew

Reputation: 634

The code looks ok. Just make sure your component is wrapped in a <Router> context.

Upvotes: 1

Related Questions