Issue
hi everyone i'm just learning react-native and i have a problem. When i execute an asynchronous method and then print in rendering the result, it's like the function doesn't finish. My code is:
export default class UserList extends Component {
constructor(){
super();
this.state={
author_name: []
}
}
async getPosts(){
var sid=this.props.route.params.value_sid
var did=this.props.route.params.value_did
const utils=new Utils();
//now i resolve the promise after a network request
const y=await utils.getPost(sid,did).then((responseJson) => {
const personArray = responseJson?.posts ?? [];
personArray.map((data) => {
//i extract the authorName field from the json file that I read from the network and set state
this.setState({
author_name: [...this.state.author_name, data.authorName],
})
})
})
}
render(){
console.log("author name is: ",this.state.author_name)
}
console.log output is:
author name is: ["Joe"]
author name is: ["Joe", "unnamed"]
author name is: ["Joe", "unnamed", "Jude"]
author name is: ["Joe", "unnamed", "Jude", "Jude"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555", "Bill"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555", "Bill", "Stacy"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555", "Bill", "Stacy", "Matt"]
author name is: ["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555", "Bill", "Stacy", "Matt", "Jess"]
instead I want to have as a result only:
["Joe", "unnamed", "Jude", "Jude", "Yuppie", "Ratatatatata55555", "Bill", "Stacy", "Matt", "Jess"]
Wow can I do?i know that with await it waits for the method to finish to get the result but in my case, wait doesn't work. Why?
Solution
Instead of calling setState while mapping, call setState on the result of the map function:
async getPosts(){
var sid=this.props.route.params.value_sid
var did=this.props.route.params.value_did
const utils=new Utils();
const responseJson = await utils.getPost(sid,did)
const author_name = (responseJson?.posts ?? [])
.map((data) => data.authorName)
this.setState({author_name})
}
Answered By - PhantomSpooks
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.