reactjsreact-reduxreact-router-dom

Redirect react-router-dom v6


I have a problem, watching a video on youtube that used history.push('/login?redirect=shipping'), how can I modify it using navigate, because if I use the string navigate ('/ login?redirect=shipping') even if logged in it returns to home page and does not go to the shipping page.

I solved the problem in this way :

 const checkoutHandler = () => {
       if(!userInfo){
          navigate('/login')
       } else{
          navigate('/shipping')
       }
    }

Solution

  • Your solution is good. Can I fill in some gaps?

    1. We need to get the state of user to check if user logged in to proceed with if statement.

    2. After this your solution will work.

      import React from 'react'
      import { useNavigate } from 'react-router-dom'
      import { useSelector } from 'react-redux'
      //....some imports
      
      const CartScreen = () => {
      //.......some code before
        const navigate = useNavigate()
        const userLogin = useSelector((state) => state.userLogin)
        const { userInfo } = userLogin
      
        const checkoutHandler = () => {
          if (!userInfo) {
          navigate('/login')
          } else {
            navigate('/shipping')
          }
        }
      
        //...return JSX...