简体   繁体   中英

Axios get multiple JSON end points and save into state (react)

I am trying to update my axios get request from 1 JSON end point to 3 JSON end points and then save the posts into the component state.

https://codesandbox.io/s/multiple-get-requests-gerjq - I have console.log(posts) but it does not seem any of the objects are being saved into the state.

Any idea where I am going wrong?

 private getPosts() {
  axios
    .all([
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www..."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "http://api...."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www..."),
      axios.get("https://cors-anywhere.herokuapp.com/" + "https://www...")
    ])
    .then(axios.spread((response =>
      response.data.map(post => ({
        id: `${ post.Id || post.jobId }`,
        name: `${ post.Name || post.advertisements[0].title.localization[1].value }`,
        company: `${ post.Company || 'Ohly' }`,
        summary: `${ post.Summary }`
      }))
    )))
    .then(posts => {
      this.setState({
        posts,
        isLoading: false
      });
    })
     // Error catching
    .catch(errors => this.setState({ errors, isLoading: false }));
}

You need to access the three responses as three arguments to axios.spread and return the mapped result

.then(
    axios.spread((response, response1, response2) => {
      return [...response.data, ...response1.data, ...response2.data].map(
        post => ({
          id: `${post.Id || post.jobId}`,
          name: `${post.Name ||
            post.advertisements[0].title.localization[1].value}`,
          company: `${post.Company || "Ohly"}`,
          summary: `${post.Summary}`,
          url: `${post.AbsoluteUrl || post.adUrl.localization[0].value}`
        })
      );
    })
  )

Working demo

I would recommend instead of normal setState, try using setState with callback function. Just replace your setState code with the code below:

this.setState({
      posts,
      isLoading: false
    }, () => {
      console.log(this.state)
    });

Instead of console.log, you can use any function as well. But your state will be updated for sure.

for axios multi request please follow this pattern

axios.all([
 axios.get('http://google.com'),
 axios.get('http://apple.com')
]).then(axios.spread((googleRes, appleRes) => {
  this.setState({google: googleRes, apple: appleRes});
});

you need to store your api data to your state in order to available the request data inside your component.

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