I have a form where i want to do input check as user enters input via onChange event.
I store user’s input in a state variable in the container (call this the form component) and use the setter to trigger a re render of the children (call this the input component) with a message if the input is not acceptable.
When the form is mounted, i see that the input component renders, but even though i change the state of the form component and pass the state as a prop to the input component, it seems to me that the input component is not re rendered.
Any ideas why and how to fix this?
Here is a sample code:
1 function RegistrationForm({setUserData, setCurrentView, coords}) {
2 const [formData, setFormData] = useState(new Map([['regGender', 'erkek']]));
3 const [messages, setMessages] = useState(new Map());
4 const [areFieldsReady, setAreFieldsReady] = useState(false);
5 const [isPhotoReady, setIsPhotoReady] = useState(false);
6
7 function handleChange({target}) {
8 setFormData(prevFormData => {
9 const formData = prevFormData.set(target.id, target.value)
10 checkRegistrationForm(formData, setMessages, setAreFieldsReady); // Updates the messages state
11 return formData;
12 });
13 }
14
15 function handleChangePhoto ({target}) {
16 setFormData(prevFormData => prevFormData.set(target.id, target.files[0]));
17 setIsPhotoReady(true);
18 }
19
20 function handleRegisterClick(e) {
21 e.preventDefault();
22 if(!areFieldsReady || !isPhotoReady) {
23 return;
24 }
25 formData.set('lat', coords.lat);
26 formData.set('lng', coords.lng);
27 registerUser(formData)
28 .then(resObj => {
29 localStorage.isLoggedIn = 'true';
30 localStorage.pid = resObj.pid;
31 localStorage.password = resObj.password;
32 setUserData(resObj);
33 setCurrentView('UserView');
34 })
35 .catch(error => alert(error));
36 }
37
38 return (
39 <div className='registrationForm'>
40 <p>Email</p>
41 <p>{messages.get('regEmail')}</p>
42 <InputEmail id='regEmail' onChange={handleChange}
43 value={formData.get('regEmail')} message={messages.get('regEmail')} />
/* Code continues */
I tried moving the paragraph element inside the input component to jsx in the form component and i still don’t get a re render: the message is not printed. I checked via breakpoints that the messages Map is updated when the return is called.