I'm dipping my toes in the React pool and can't seem to get my head round one aspect mainly around the amount of times the function renders the page.
Using the below example when the form validation fails I see the toast display TWICE.
The toast I am using is react-hot-toast
My understanding is that;
The page first renders and
formErrorsfrom theuseState()is empty.When the submit button is pressed it calls the onSubmit function and if the form fails validation it fires
setFormErrorsfunctionThis causes a re-render of the page, while also populating the
formErrorsvariableAs
formErrorsis not falsy etc it then fires thetoastfunction.
But when I check the console I see it has fired toast twice and I see two toasts, this means it's rendered twice? Why is this?
Am I going about this all the wrong way? Is there a better method of using a function like toast to display messages? Should I be putting it all in a context (might not be right terminology) ?
export default function RegistrationPage() {
const [formErrors, setFormErrors] = useState({})
const passwordField = useRef()
const password2Field = useRef()
useEffect(()=>{
usernameField.current.focus()
})
const onSubmit = (ev) =>{
ev.preventDefault()
if(passwordField.current.value !== password2Field.current.value){
setFormErrors({"password2": "Passwords do not match"})
}else{
console.log("Need to implement")
}
}
if(formErrors && Object.keys(formErrors).length > 0){
toast('Here is your toast.');
console.log("Toast Fired");
}
return (
<Body>
<h1>Login</h1>
<Form onSubmit={onSubmit}>
<InputField fieldRef={usernameField} name="username" label="Username" error={formErrors?.username}></InputField>
<InputField fieldRef={emailField} name="email" label="Email Address" type="email" error={formErrors?.email}></InputField>
<InputField fieldRef={passwordField} name="password" label="password" type="password" error={formErrors?.password}></InputField>
<InputField fieldRef={password2Field} name="password2" label="password again" type="password" error={formErrors?.password2}></InputField>
<Button variant="primary" type="submit">Register</Button>
</Form>
</Body>
);
}
toasthere in order to render something. Even the docs seem to say that this function isn't supposed to be used in React. You want to use the<Toaster>component and render it conditionally depending on the value offormErrors.toast? It actually saysCall it to create a toast from anywhere, even outside React. Make sure you add the <Toaster/> component to your app first.Which I've already added the component to the<Body>