I am a beginner in React and TypeScript and I am facing an issue while trying to implement a basic functionality. Unfortunately, I keep encountering the error: Unhandled Rejection (TypeError): setToken is not a function. Can anyone provide me with some guidance?
App.tsx
import React from "react"
import './App.css';
import VacationManager from "./VacationManager";
import Login from './Login';
function App() {
const [token, setToken] = React.useState<string | null>(null);
if(!token) {
return <Login setToken={setToken} />;
}
return <div className="App">
<div className="Header"></div>
<div className="App-Body">
<VacationManager />
</div>
</div>;
}
export default App;
Login.tsx
import React from 'react';
import PropTypes from 'prop-types';
import './Login.css';
async function loginUser(credentials: { username:string | null, password:string | null }) {
return (credentials.username === "test" && credentials.password === "test") ? "new_login_state" : null;
}
function Login(setToken: React.Dispatch<React.SetStateAction<string | null>>) {
const [username, setUserName] = React.useState<string | null>(null);
const [password, setPassword] = React.useState<string | null>(null);
const handleSubmit = async (e: { preventDefault: () => void; }) => {
e.preventDefault();
const token = await loginUser({
username,
password
});
setToken(token);
}
return <div className="login-wrapper">
<h1>Please Log In</h1>
<form onSubmit={handleSubmit}>
<label>
<p>Username</p>
<input type="text" onChange={e => setUserName(e.target.value)}/>
</label>
<label>
<p>Password</p>
<input type="password" onChange={e => setPassword(e.target.value)}/>
</label>
<div>
<button type="submit">Submit</button>
</div>
</form>
</div>;
}
Login.propTypes = {
setToken: PropTypes.func.isRequired
}
export default Login;
Upon entering the username and password, I encounter the aforementioned error. My intention is to pass the setter to the Login component for updating the token status. This example serves as a simple starting point, yet I seem to be missing something in my implementation.