javascript - Redux redux-think Load Async data before React component is mounted -
i new redux , reactjs, , having issues load data before react component mounted.
i have userpage container linked redux store
container/user-page.js
class userpage extends page { componentwillmount() { this.props.userlist(); } title() { return 'user management'; } breadcrumb() { return [ { title: 'home', icon: 'fa-users' }, { title: this.title(), active: true } ]; } /** * content loaded page */ content() { console.log(this.props); if(this.props.fetched) { console.log('fetching now...'); console.log(this.props.payload); } return ( <div classname="row"> {/* left column */} <div classname="col-md-6"> {/* general form elements */} <div classname="box box-primary"> <div classname="box-header with-border"> <h3 classname="box-title">new user</h3> </div> {/* /.box-header */} <userform onusersubmit={this.handleusersubmit}/> </div> {/* /.box */} </div> {/*/.col (left) */} {/* right column */} <div classname="col-md-6"> {/* userlist made of <user /> */} <userlist userlist={this.props.userlist} /> {/* /.box */} </div> {/*/.col (right) */} </div> ); } }
userpage redux container connected store through following code
function mapstatetoprops(state) { return { userlist: state.userlist, fetched: state.fetched, payload: state.payload } } function matchdispatchtoprops(dispatch) { return bindactioncreators( { userlist: useraction.userlist, }, dispatch); } export default connect(mapstatetoprops, matchdispatchtoprops)(userpage);
i this.props.userlist() action creator dispatch user_list , load data api here action creator.
actions.js
import axios 'axios'; class useraction { static userlist() { console.log('user list fired...'); const request = axios.get('http://example.local/api/user'); return (dispatch) => { dispatch({ type: 'fetch_users_start', fetched: false }); request.then(function(response) { console.log('user data...'); console.log(response.data); dispatch({ type: 'user_list', fetched: true, payload: response.data }); }).catch((err => { dispatch({ type: 'fetch_users_error', fetched: false }); })); } } } export default useraction;
i know above code not work, componentwillmount not wait async callback resolve , render component. question right approach load async data before component mounted, or make compoenentwillmount wait this.props.userlist() resolve request , render?
Comments
Post a Comment