0

I have navbar component with sign in link that is linked to login page. I have handleLogin function in navbar component and I want pass it through the link and call it in login component.

How to pass this method? I tried using query and getServerSideProps but that's not working.

here is navbar component:

const Navbar = ({token}:{token:string|null}) => {
var [loggedIn,setLoggedIn]=false;
 const handleLogin=()=>{
    localStorage.removeItem("token")
    setLoggedIn(true)
   
   }
return (

    <>
      {
      
       loggedIn==true ? (
          
          <Link href={"#"}><a href="" onClick={handleLogOut} className="nav-link">log out <FontAwesomeIcon icon={faUser}/></a></Link>
        ):(
        //this is the link that I want it to pass handleLogin function
          <Link  href={{pathname:"/login",query:{handleLogin:handleLogin}}}><a href="" className="nav-link">Sign in <FontAwesomeIcon icon={faUser}/></a></Link>
        )
      }
</>
)
}

and this is the login page:

const Login = ({handleLogin}:{handleLogin:(...args:any[])=>void}) {

const [errors, setErrors] = useState([])
const validate=async()=>{
  try{
    const validateResult= await schema.validate(user,{abortEarly:false})
    setErrors([])
   return true
  
  }
 
  catch(er:any){
        console.log(er.errors)
         //@ts-ignore
        setErrors(er.errors)
        return false
  }
        
          
}

  const handleSubmit=async(e:React.SyntheticEvent)=>{
        e.preventDefault();
        const validateResult=await validate()
       if(validateResult==true){
        console.log(JSON.stringify(user))
        try{
          const response=await axios.post(`https://reqres.in/api/login`,user)
          console.log(response.data)
          const token=response.data.token;
          localStorage.setItem("token",token)
          handleLogin()
        }
        catch(er){
          //@ts-ignore
        setErrors(["The username or password is incorrect"])
        localStorage.setItem("token","")
        }
       
       
       }
    
        
     }


     const handleChange=(e:React.ChangeEvent<HTMLInputElement>)=>{
        setUser({...user,[e.currentTarget.id]:e.currentTarget.value})
     }

}


 return (
  <>
   <h5>to see the successfull login use:
    email:[email protected],
    password:"cityslicka"
  </h5>
  <div className="wrapper fadeInDown">
   
     
    
  <div id="formContent">
    {errors.length!=0 && (
       <div className="vali">
       {errors.map((el:any)=>{
          
             return <>
                      
                       <div key={el.id} className="error-list">
                       {el}
                       </div>
                      
                      
                 
             
             </>
           })}
            </div>
    )}
 

 
    <div className="fadeIn first">
      Login
    </div>

  
    <form onSubmit={handleSubmit}>
    
    <div className="form-floating form-outline">
      <input type="text"  id="email" className="fadeIn second form-control" placeholder='Mobile Phone' onChange={handleChange} />
      <label className="form-label" htmlFor="email">Email</label>
     </div>  
     <div className="form-floating form-outline">
      <input type="password"  id="password" className="fadeIn second form-control" placeholder='Password' onChange={handleChange}/>
      <label className="form-label" htmlFor="password">Password</label>
     </div>
     
      <input type="submit" className="fadeIn fourth "  value="Log In"/>
      
    </form>

    
    <div id="formFooter">
      <a className="underlineHover" href="#">Forgot Password?</a>
    </div>

  </div>
</div>



  </>
  )

export const getServerSideProps = async(context:any) => {
  console.log(context.query) 
 
  

 
  return {
      props: { 
         handleLogin: context.query.handleLogin //pass it to the page props
      }
  }
}
export default Login;

When I try my code I see this error:

Type '() => void' is not assignable to type 'string | number | boolean | readonly string[] | readonly number[] | readonly boolean[] | null | undefined'.

2
  • 2
    As the error mentions, you can't pass a function as a query param in Link. Commented Jun 28, 2022 at 11:42
  • @juliomalves oh no! Commented Jun 28, 2022 at 12:25

1 Answer 1

1

You cant pass methods and functions via Link.

Now, you can use a contexts to share methods/functions/props between pages.

Moreover, if you want to keep some kind of props you can use window storage / cookie.

Sign up to request clarification or add additional context in comments.

2 Comments

@tnx I used localstorage in my code(as you see above) to set token . but when i try to use localstorage(token) to another component(navbar), It delayed in changing state and I should refresh the page to see the changes. so i have to change state(loggedIn) directy after login!
using context was good idea and worked for me tnx!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.