I want to use the function handleSubmit in other file, how i can export this function?
If i try to export this function this error appear "Modifiers cannot appear here".
export default function LoginPage(props) {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [errorMessage, setErrorMessage] = useState("");
const navigate = new useNavigate();
const handleSubmit = async (event) => {
event.preventDefault();
const response = await fetch("http://localhost:5000/logUser");
const data = await response.json();
const user = data.find(
(user) => user.email === email && user.password === password
);
if (user) {
// Login successful
if (user.categoryId === 1) {
return true;
} else if (user.categoryId === 2) {
return true;
}
} else {
setErrorMessage("Invalid email or password");
return false;
}
};
return (
<div className="LoginPage"></div>
);
}
I have tried to export but i can’t.
2
Answers
The easiest way is to get the
handleSubmit
function out of the component like this:Then, in other files, you can import
handleSubmit
. Note that you’ll have to modify thehandleSubmit
function.However, I recommend you check custom hooks as well. It’s the proper solution: https://beta.reactjs.org/learn/reusing-logic-with-custom-hooks
There are two ways that I see:
This way it creates a cleaner and more understandable code base…if you weren’t using the submit function anywhere else than I’d say keep it in your current component that is using it, otherwise it might be better to separate it for ease of use.