Reputation: 1313
I have the following react-native program:
class offerDetail extends Component {
constructor(props) {
super(props);
this.state = {
phone: null,
logo: null,
instagram: null
};
const { name } = this.props.doc.data();
this.ref = firebase.firestore().collection('companies').doc(name);
}
componentWillMount() {
let docObject = null;
this.ref.get().then(doc => {
let docObject = doc.data();
console.log(docObject); -----------------------------1
});
this.setState(
docObject
);
console.log(this.state); --------------------------------2
}
render() {
console.log(this.state);--------------------3
...
......
I have 3 instances where I print to the console. Only in instance number 1 does it print non null values, however, in instance 2 and 3 it prints null values. Why is instance 2 printing null if it is called right after setState?
Can it be that its not setting the state correctly and why?
Upvotes: 0
Views: 111
Reputation: 8784
setState()
in React is asynchronous.
From the React docs (3rd paragraph):
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback...
If you want to access the state once it has been updated, you can add a callback like so:
this.setState({ docObject }, () => {
console.log(this.state.docObject);
});
Upvotes: 1