LuisBV
LuisBV

Reputation: 53

Edit Form React JS

I´m making an edit form with React js. I have multiple components in the form. In one of the son components, I pass all the changes that I`ve done to a hook in the main component to do the changes in firebase.

Father Component

const [changes, setChanges] = useState({});
const updateGenData = (genData) => {
    setChanges(genData);  
  }

Son Component(I take all the info from the father, via props)

const UpdateProfileGenData = (props) => {

 const [values, setValues] = useState({});
 const [changes, setChanges] = useState({});

 useEffect(() => {
    setValues(props);
 },[props]); 

 const {field1, field2, field3} = values;

 useEffect(() => {
    props.updateGenData(changes);
},[changes]); 

  const handleChange= e => {
        setValues({
            ...values,
            [e.target.name]: e.target.value
        });
         setChanges({
          ...changes,
          [e.target.name]: e.target.value
      }) 
    }
return (

<input type="text" name="field1" value={field1} onChange={handleChange}/>
<input type="text" name="field2" value={field2} onChange={handleChange}/>
<input type="text" name="field3" value={field3} onChange={handleChange}/>

);
}
export default UpdateProfileGenData;

When I pass the values ​​from the child component to the parent it doesn't allow me to edit the child form . I can´t change any field.

Any suggestions??

Regards

Upvotes: 0

Views: 1514

Answers (1)

Vadim Rogov
Vadim Rogov

Reputation: 270

Why do you use useEffect so often? The problem may be that you often use useEffect and somewhere you overwrite the data correctly. Can be made easier:

Father Component

const [changes, setChanges] = useState({});
const updateGenData = (genData) => setChanges({...changes, ...genData});  

Son Component

const UpdateProfileGenData = ({field1, field2, field3, updateGenData}) => {

  const handleChange= e => updateGenData({
            [e.target.name]: e.target.value,
        });

return (

<input type="text" name="field1" value={field1} onChange={handleChange}/>
<input type="text" name="field2" value={field2} onChange={handleChange}/>
<input type="text" name="field3" value={field3} onChange={handleChange}/>

);
}
export default UpdateProfileGenData;

Upvotes: 1

Related Questions