Issue summary Hi Team, I am new to Polaris and trying to create react signup form with following code
import React, { useCallback, useState } from "react";
import {
Button,
Form,
FormLayout,
Layout,
Checkbox,
Card,
Page,
TextField,
} from "@shopify/polaris";
export const SignIn = () => {
const [textFieldValue, setTextFieldValue] = useState("Mark");
const [newsletter, setNewsletter] = useState(false);
const [email, setEmail] = useState("mark@hello.com");
const [password, setPassword] = useState("password");
const [loading, setLoading] = useState(false);
const handleNewsLetterChange = useCallback(
(value) => setNewsletter(value),
[]
);
const handleEmailChange = useCallback((value) =>{setEmail(value)}, [email]);
const handlePasswordChange = useCallback((value) => setPassword(value), [password]);
const handleTextFieldChange = useCallback(
(value) => setTextFieldValue(value),
[textFieldValue]
);
const handleSubmit = useCallback((_event) => {
// setLoading(true);
console.log(textFieldValue,newsletter,email, password )
}, []);
const signupForm = (
<Form onSubmit={handleSubmit} preventDefault={true}>
{console.log(email)}
<FormLayout>
<TextField
label="Name"
value={textFieldValue}
onChange={handleTextFieldChange}
error={textFieldValue ? "" : "Name is required"}
/>
<TextField
value={email}
onChange={handleEmailChange}
label="Email"
type="email"
error={email ? "" : "Email is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<TextField
value={password}
onChange={handlePasswordChange}
label="Password"
type="password"
error={password ? "" : "Password is required"}
helpText={
<span>
We’ll use this email address to inform you on future changes to
Polaris.
</span>
}
/>
<Checkbox
label="Sign up for the newsletter"
checked={newsletter}
onChange={handleNewsLetterChange}
/>
<Button
submit
primary={true}
loading={loading}
fullWidth={true}
id="marketing-button"
>
Create your account
</Button>
</FormLayout>
</Form>
);
return (
<Page>
<Layout>
<Layout.Section secondary>
<Card title="Signup" sectioned>
{signupForm}
</Card>
</Layout.Section>
</Layout>
</Page>
);
};
When Onchange all the values are getting updated but with onsubmit useCallback I am getting only old values which assigned using useState, I tried with onsubmit as a normal function like below code its working
const handleSubmit = () => {
console.log(textFieldValue,newsletter,email, password )
}
Expected behavior Since I wanted to send all the data to API please educate me how to do this with useCallback or else I can go with normal onSubmit function
You missed some dependencies in useCallback
const handleSubmit = useCallback((_event) => {
console.log(textFieldValue,newsletter,email, password )
}, [textFieldValue,newsletter,email, password]);