How to use hooks in callback function

Viewed 44

When the else condition is triggered in the callback function, I am using useHistory hook to redirect, but am getting an error showing:

Uncaught TypeError: Cannot read properties of undefined (reading 'push')

I tried using Redirect as well, but it did not redirect but the welcome message alert is showing

The code:

  export default function Deposit() {
  const [alanInstance, setAlanInstance] = useState();
  const { isAuth } = useSelector((state) => state.login);
  const dispatch = useDispatch();
  let history = useHistory();


  const depositPage = useCallback(() => {
    if (!isAuth) {
      alanInstance.playText("You are not logged in, please login")
    } else {
      alanInstance.playText("You are going to start your deposit")
      alert('Welcome Message'); 
      history.push("/deposit");
    // return <Redirect to='/deposit' />
    }
  }, [alanInstance, isAuth ])

}
2 Answers

I'll take a stab at it. Try checking history first and add it to the dependency array:

const depositPage = useCallback(() => {
if (!isAuth) {
  alanInstance.playText("You are not logged in, please login")
} else {
  alanInstance.playText("You are going to start your deposit")
  alert('Welcome Message'); 
  if (history) history.push("/deposit");
// return <Redirect to='/deposit' />
}
}, [alanInstance, isAuth, history ])

I found the cause of the error. I am trying to use useHistory hook without wrapping my app with BrowserRouter. All I had to do is to warp my app component with BrowserRouter

 <BrowserRouter>
    <App />
 </BrowserRouter>
Related