Reputation: 593
I am stumped on the below bug or my lack of understanding about why my update to setState is not working. I read several questions saying setState isn't instant so I inserted some delays but it doesn't seem to change matter. Why is my setState call at the end not working?
import React, { Component } from 'react';
import { View, Text, FlatList, TextInput, ListItem } from 'react-native';
class SearchFunction extends Component {
constructor(props) {
super(props);
this.state = {
data: [],
value: '',
};
this.arrayNew = [
{ name: 'Robert' },
{ name: 'Bryan' },
{ name: 'Vicente' },
{ name: 'Tristan' },
{ name: 'Marie' },
];
setTimeout(1000);
this.setState({data: this.arrayNew}, console.log(this.state));
setTimeout(1000);
console.log(this.state)
}
The above console logs show that data is still []. Whereas I expected it to be this.arrayNew
Upvotes: 0
Views: 63
Reputation: 52347
setTimeout
takes two parameters: a callback and a time interval. Calling setTimeout(1000)
doesn't do anything
this.setState
shouldn't be called in the constructor
-- your state inside the constructor should be set by this.state =
like you have above
Your syntax for this.setState
isn't correct -- the first parameter is correct (the state object), but the second parameter should be a callback function (see my example)
Let's look at an example of a working function with some different places that print the state:
class SearchFunction extends React.Component {
constructor(props) {
super(props);
this.state = {
data: [],
value: '',
};
console.log("Initial state:")
console.log(this.state)
this.arrayNew = [
{ name: 'Robert' },
{ name: 'Bryan' },
{ name: 'Vicente' },
{ name: 'Tristan' },
{ name: 'Marie' },
];
setTimeout(() => {
this.setState({data: this.arrayNew}, () => {
console.log("Newly set state:")
console.log(this.state)
});
}, 1000);
}
render() {
return <View/>;
}
}
Snack example: https://snack.expo.io/4kVsJHJ0d
this.state =
you can see the state is emptysetTimeout
with a callback function and an interval of 1 secondthis.setState
with an arrow function as the callback. You can see that after it runs, it calls its own callback function, which prints the updated state.Upvotes: 2