Reputation: 95
I have a Form and it's working ok sending data to the Cloud Database. When the page is loaded for the first time renders the data from the database, but when this data is updated using the form, doesn't change. I don't know how to render it again. I think it's using useEffect.
Here some code:
const user = useContext(UserContext);
const { userName, position, phoneUser } = user;
const initialStateValues = {
userName: "",
phoneUser: "",
position: "",
};
const [values, setValues] = useState(initialStateValues);
const handleInputChange = e => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
const handleSubmit = e => {
e.preventDefault();
setValues({ ...initialStateValues });
const usuario = firestore.collection('users').doc(user.uid);
usuario.set(
{
userName: values.userName,
phoneUser: values.phoneUser,
position: values.position,
},
{ merge: true }
);
};
useEffect(() => {
}, []);
And the render part here:
<p>
<b>Contact Name:</b>
{userName}
</p>
<p>
<b>Phone:</b>
{phoneUser}
</p>
<p>
<b>Posición:</b>
{position}
</p>
Upvotes: 0
Views: 535
Reputation: 5054
This is because you are rendering values from the user
object. But during the form change you are updating the state values. What you can do is initialize the state using the user object. And then show data from the state.
const user = useContext(UserContext);
const { userName, position, phoneUser } = user;
// Updated the initialStateValues with values from the user.
const initialStateValues = {
userName,
phoneUser,
position,
};
const [values, setValues] = useState(initialStateValues);
const handleInputChange = e => {
const { name, value } = e.target;
setValues({ ...values, [name]: value });
};
const handleSubmit = e => {
e.preventDefault();
setValues({ ...initialStateValues });
const usuario = firestore.collection('users').doc(user.uid);
usuario.set(
{
userName: values.userName,
phoneUser: values.phoneUser,
position: values.position,
},
{ merge: true }
);
};
useEffect(() => {
}, []);
And in the render part,
<p>
<b>Contact Name:</b>
{values.userName}
</p>
<p>
<b>Phone:</b>
{values.phoneUser}
</p>
<p>
<b>Posición:</b>
{values.position}
</p>
Upvotes: 1