I am having a problem updating a state. I fetch a JSON result using an address set as 'newurl' and display contents in a FlatList. It all works good and I have a button that when clicked updates the 'newurl' state and reloads the data. The problem is it needs clicking twice to update the state? I have tried putting the setState in a different class but does not work Also I have can not make new 'newurl' to include the state of 'newuser'
The onclick to update the state and reload the data which updates after 2 clicks is :
onPress = () => {
this.setState({
newurl: 'https://www.newtesturl'
}),
fetch(this.state.newurl)
.then(response => response.json())
.then((response)=> {
this.setState({loading: false,list: response.data})
})
}
The problem with making the 'newurl' string when updating it, I cannot seem to add another data state into it. If I use the code below, the 'newurl' is pretty much as is it, without adding the 'newuser' state?
this.setState({
loading: true,
newurl: 'https://www.example.com/userid={this.state.newuser}'
});
Its really annoying because when I add that into a direct url like below it works?
<Image source={{uri: `https://www.example.com/userid={this.state.newuser}`}} />
This is how I am setting up my props in case it makes a differnce? :
type Props = {};
export default class App extends Component<Props> {
constructor(props) {
super(props);
this.state = { list: [], loading: false, newuser: '10101', newurl: '' };
}
Sorry if I have not explained it that well but if you need anything clarifying please ask, thanks
CodePudding user response:
State Updates May Be Asynchronous. See here for more info.
Second issue is because you don't use template string there. See here for more info.