简体   繁体   中英

Multiple Axios GET requests from different components

I have 2 different components that render in main screen. Both have multiple axios.get requests to fill some data. But at first page load only the last component returns data and the first one is waiting for like 60 seconds to fill it's data. I don't know if it's React issue or my express server issue so here is the sample codes

Main.JS

class App extends Component {
  render() {
    return (
      <div>
        <ComponentA />
        <ComponentB />
      </div>
    );
  }
}

ComponentA.JS

 async componentDidMount() {
        const live = await axios.get('api link');
        const current = await axios.get('api link');
        this.setState({
            some states
        })
    }

ComponentB.JS

async componentDidMount() {
        const live = await axios.get('api link');
        this.setState({
            some states
        })
    }

express.js

var express = require('express');
var app = express();
var sql = require('mssql');

app.use(function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Credentials", "true");
    res.header("Access-Control-Allow-Headers", "Origin,Content-Type, Authorization, x-id, Content-Length, X-Requested-With");
    res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
    next();
});

var server = app.listen(8081, function () {
    var host = server.address().address
    var port = server.address().port
});

app.get('/api', function (req, res) {
    res.end(some values)
})

Personally I'd just chain axios calls with .then()

    axios.get('api link').then(data => {
    let live = data
    axios.get('api link2').then(data2 =>
    let current = data2
         })
    })

That's without diving into all of your components and lifecycle events..but might be helpful I hope.

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