Reputation: 175
I am trying to store the value of one state property within another on submit, so that I can submit a URL friendly slug to my database.
Below is part of the function that is called when my form is submitted. Currently the form submits to a database (Firestore) and it works fine. However, I need to collect the value that a user inputs into streetAddress, slugify it, and then submit that to my database as its own slug field using the slug property of my state.
The problem I have, is I don't know how to do this. I've tried a few ways and slug is submitted to the database, but always with an empty value. Below is how I have attempted it.
onSubmit = event => {
const { reviewTitle, reviewContent, streetAddress, cityOrTown,
countyOrRegion, postcode, startDate, endDate, landlordOrAgent, rating, slug } = this.state;
this.setState({
slug: streetAddress
})
// Creating batch to submit to multiple Firebase collections in one operation
var batch = this.props.firebase.db.batch();
var propertyRef = this.props.firebase.db.collection("property").doc();
var reviewRef = this.props.firebase.db.collection("reviews").doc();
batch.set(propertyRef, { streetAddress, cityOrTown,
countyOrRegion, postcode, slug,
uid });
batch.set(reviewRef, { startDate, endDate,
reviewTitle, reviewContent, rating,
uid });
batch.commit().then(() => {
this.setState({ ...INITIAL_STATE });
});
event.preventDefault();
};
Can anyone point me in the right direction or tell me what I'm doing wrong?
Upvotes: 0
Views: 230
Reputation: 1914
this.setState
is a async function. So what you can do is calling a callback function after the state is updated.
this.setState({
slug: streetAddress
}, () => {
// Creating batch to submit to multiple Firebase collections in one operation
var batch = this.props.firebase.db.batch();
var propertyRef = this.props.firebase.db.collection("property").doc();
var reviewRef = this.props.firebase.db.collection("reviews").doc();
batch.set(propertyRef, {
streetAddress, cityOrTown,
countyOrRegion, postcode, slug,
uid
});
batch.set(reviewRef, {
startDate, endDate,
reviewTitle, reviewContent, rating,
uid
});
batch.commit().then(() => {
this.setState({ ...INITIAL_STATE });
});
event.preventDefault();
})
Upvotes: 1