简体   繁体   中英

Axios multiple Requests in React

I am trying to create 2 requests and set variables with this.setState({}) for further changes.

This is what i got:

 class App extends React.Component { constructor() { super(); this.state = {user: false, repository :false} } componentDidMount() { axios.all([ axios.get('https://api.github.com/users/antranilan'), axios.get('https://api.github.com/users/antranilan/repos') ]) .then(axios.spread(function (userResponse, reposResponse) { this.setState({user : userResponse.data, repository : reposResponse.data}); }); } render() { return ( <div> {this.state.user.login} {this.state.repository.length} </div> ) } } ReactDOM.render(<App />, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

I looked up through multiple questions with what i am trying to do but there was no solution to what i am trying to achive.

You have binding issue in your code.

 class App extends React.Component { constructor() { super(); // You should use object to delineate the type this.state = {user: {}, repository :{} } } componentDidMount() { // Better use native Promise.all Promise.all([ axios.get('https://api.github.com/users/antranilan'), axios.get('https://api.github.com/users/antranilan/repos') ]) // use arrow function to avoid loosing context // BTW you don't need to use axios.spread with ES2015 destructuring .then(([userResponse, reposResponse]) => { this.setState({user : userResponse.data, repository : reposResponse.data}); }); } render() { const { user, repository } = this.state return ( <div> {user && user.login} {repository && repository.length} </div> ) } } ReactDOM.render(<App />, document.getElementById('app')); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="app"></div> 

UPDATE as @JaromandaX pointed out you'd better stick with native Promise.all and destructuring.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM