Reputation: 1401
How can I prevent my document query from being run constantly. I want to retrieve the document value only once. In my code I have this. When the user tries typing in the form it is running the following code block and preventing updates to the form.
var docRef = store.collection('users').doc(props.route.params.user.id)
docRef.get().then((doc) => {
if (doc.exists) {
setInterests(doc.data().interests);
setAbout(doc.data().about);
}
});
For example this form isn't updating because of the query.
<TextInput
multiline
numberOfLines={3}
placeholder="About Me"
placeholderTextColor="#666666"
value={about}
onChangeText={setAbout}
style={[styles.textInput, {height: 90}]}
Upvotes: 0
Views: 156
Reputation: 13588
Assuming you are using functional component, the minimal code to run any code only once when component mount is as follows
useEffect(() => {
var docRef = store.collection('users').doc(props.route.params.user.id)
docRef.get().then((doc) => {
if (doc.exists) {
setInterests(doc.data().interests);
setAbout(doc.data().about);
}
});
},[])
If you want to run an effect and clean it up only once (on mount and unmount), you can pass an empty array ([]) as a second argument. This tells React that your effect doesn’t depend on any values from props or state, so it never needs to re-run. This isn’t handled as a special case — it follows directly from how the dependencies array always works.
https://reactjs.org/docs/hooks-effect.html
If you’re familiar with React class lifecycle methods, you can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined.
Upvotes: 1