reactjs - React: Child component is passing it's state up to parent, but once parent has it, the parent is not updating its state -
my issue here have values coming searchform component. they're passing correct value arguments handlesearch function, call setstate nothing. i've included console.logs show what's stored in variables. see comments in code below.
because state being passed component resultlist component empty strings, resultlist not render correctly.
import react, { component } 'react'; import axios 'axios'; import searchform './components/search_form'; import resultlist './components/results_list'; class app extends component { constructor(props) { super(props); this.state = { category: '', term: '', results: [] }; this.handlesearch = this.handlesearch.bind(this); } handlesearch(category, term) { //this not setting state!!!!! this.setstate({ category, term }); //the first 2 console.logs log arguments function //the last 2 console.logs log empty strings after above setstate call. console.log("received form: " + category); console.log("received form: " + term); console.log("#################################"); console.log(this.state.category); console.log(this.state.term); console.log('http://swapi.co/api/' + category + '/?search=' + term); axios.get('http://swapi.co/api/' + category + '/?search=' + term).then((response) => { let results = response.data.results; this.setstate({ results }); console.log(this.state.results); }).catch((error) => { console.log(error); }); } render() { return ( <div classname="container panel panel-default"> <searchform handlesearch={this.handlesearch}/> <resultlist results={this.state.results} category= {this.state.category}/> </div> ); } } export default app;
i'll elaborate on said in comment:
component#setstate defers , batches state update requests performance. because of this, cannot relay on component.state updated new values after call.
setstate provides second argument - callback called after state update operation performed. in case, like
this.setstate({ category, term }, () => { console.log(this.state.term, this.state.category) // can use them })
Comments
Post a Comment