ReactJS: combine 2 JSON responses from get request

http batch requests
axios multiple get requests
combine multiple requests in one http call using json batching
axios sequential requests
react get json value by key
axios response to json
how to make multiple api calls
react native axios get example

So, I have this code that returns all of the data that can be retrieved from the endpoint. My endpoint has pagination: it only displays 10 datas per page. so my first endpoint: Link + "api/materials/?page=" + page; where page = 1, returns the first 10 data. then I have a second page so the for loop will now run Link + "api/materials/?page=" + page; where page = 2 and will return a different set of datas. What I want to happen is that all the results from both endpoints will be displayed simultaneously, if I have 10 datas in my first endpoint, and 6 datas in my 2nd run of the endpoint, I want to be able to see 16 datas in my table. What happens now is that, when the loop starts and runs the first endpoint, it displays all the data from page 1, and then when it loops again and runs page 2, the data from page 1 will be replaced with page 2. I want to combine the data from page 1 and 2.

please help me.

import React, {Component} from 'react';
import { Table } from 'semantic-ui-react'
import Link from './Link';
import axios from 'axios';
import _ from 'lodash';

class Material extends Component {
    constructor(props){
      super(props);
      this.state={
        materials: []
    }
   }

   componentDidMount() {
    const token = localStorage.getItem('jwt');
    const total = localStorage.getItem('totalpage');
    var page;
    for (page = 1; page <= total ; page++) {
        const apiBaseUrl = Link + "api/materials/?page=" + page;

        const config = {
         headers: {
           'Authorization': "bearer " + token,
           'Accept': 'application/json',
           'Content-Type': 'application/json',
         }
        }

        axios.get(apiBaseUrl, config)
         .then((response) => {
             console.log(response.data);
            this.setState({
             materials: response.data
           })
          })
    }

   }

    render() {
        const { materials } = this.state;

        let returndata = _.isEmpty(materials) ? [] : materials.data

        return (  
            <div className="ui container"> 
            <br />
            <br />
                <Table fixed>
                    <Table.Header>
                        <Table.Row>
                            <Table.HeaderCell>UUID</Table.HeaderCell>
                            <Table.HeaderCell>Title</Table.HeaderCell>
                            <Table.HeaderCell>Description</Table.HeaderCell>
                        </Table.Row>
                    </Table.Header>

                    <Table.Body>
                    {returndata.map((item, i) => {
                        return (
                        <Table.Row key = {i}>
                            <Table.Cell>{item.uuid}</Table.Cell>
                            <Table.Cell>{item.title}</Table.Cell>
                            <Table.Cell>{item.description}</Table.Cell>
                        </Table.Row>
                        )
                    })}
                    </Table.Body>
                </Table>
            </div>
      );
    }
  }
  export default Material;

Replace your .then of axios with this

.then((response) => {
        let tempState = [...this.state.materials];
        tempState.push(response.data)
        this.setState({
         materials: tempState
       })

This will copy the state to another variable and push the new data into the new variable (tempState) and replace the state with tempState which now contains the previous state data and the new data

combine two api url to one output · Issue #2316 · axios/axios · GitHub, I am trying to combine two api json url, adding to the first key and add objects so by trying to map the task key in react I do not get the object keys in the rendered component. isLoading = true; await axios .get('/sets') .then(async response prints the final output which updated by the inner get request. Simple POST request with a JSON body using fetch. This sends an HTTP POST request to the JSONPlaceholder api which is a fake online REST api that includes a /posts route that responds to POST requests with the contents of the post body and an id property.


That's because you're replacing the materials object in the state with the newly returned data.

Call some function which will update your state.

axios.get(apiBaseUrl, config)
.then((response) => {
    console.log(response.data);
    this.updateMaterials(response.data);
 })

Now update your state in that function as First retrieve the old list and then concat the new list in it, and then store it to your state.

updateMaterials = (data) => {
    let updatedList = this.state.materials.slice();
    updatedList = updatedList.concat(data);
    this.setState({materials: updatedList});
}

Also remove data from materials.

change

let returndata = _.isEmpty(materials) ? [] : materials.data

to

let returndata = _.isEmpty(materials) ? [] : materials

How to send multiple requests using Axios, After that, we define that we want to perform a GET request using axios on the above URL. responses[1] const responesThree = responses[2] // use/access the results })).catch(errors => { // react on errors. }) package.json. fetch('api/user') call performs a HTTPS GET requests to api/users the above json data is returned. The returned data is encapsulated in a Promise. We resolved the Promise to get the users array in the json, the result of the Promise resolution is used to update the state using this.setState(). The state is updated in the component's render JSx markup.


Looking at your componentDidMount method. You can extend the current state object property instead of replacing it like this:

componentDidMount() {
  const token = localStorage.getItem('jwt');
  const total = localStorage.getItem('totalpage');
  var page;
  for (page = 1; page <= total ; page++) {
    const apiBaseUrl = Link + "api/materials/?page=" + page;

    const config = {
       headers: {
         'Authorization': "bearer " + token,
         'Accept': 'application/json',
         'Content-Type': 'application/json',
       }
    }

    axios.get(apiBaseUrl, config)
     .then((response) => {
        console.log(response.data);
        this.setState((prevState) => ({
          materials: prevState.materials.concat(response.data)
        }));
      })
  }
}

Combine multiple requests in one HTTP call using JSON batching , JSON batching allows you to optimize your application by combining multiple First JSON batch request; Request format; Response format  The JSON response you get has been placed on AWS — that’s what we will use for this tutorial. As we did before, let’s create our component and set up some default state. class App extends React.Component { state = { isLoading: true, posts: [], error: null } render() { <React.Fragment> </React.Fragment> } }


How to Display Key and Value Pairs from JSON in ReactJS , JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy to read and write and for machines to parse and generate. part easily, let's assume a JSON name can have two types of values, a leaf value or a Objects are not valid as a React child (found: object with keys { a, b, c }). Consuming REST APIs With React.js In this post, we go through a tutorial on how to create a React application that can perform CRUD functions and take in data from a RESTful API. by


Sync up multiple Promises to a single result set with Promise.all, For example: A http request (e.g. using fetch ) returns a single Promise So response.json() does the job to transform the response data to a JSON object. Learn about React concepts, helpful libraries or get tips & tricks for  As Sam Torso mentioned, Object.assign is the most straightforward approach. Normally, I’d just upvote that and move on…. but there’s a few missing gotchas/points of awareness.


json-api-normalizer: An Easy Way To Integrate The JSON API And , Simple Demo React Application we will build by the end of the article This is possible because, before you send the API response to the store, you So, here we are getting the User data object with an ID of 1 and a name of Another request would return a User with the ID of 2 and the name of Kevin :. Question: How to return both data sets (from List Projects and HTTP request to SharePoint) as a single result set in the Response step. I would put this into a collection in PowerApps and would expect it to appear as a two column table/record with the result set from List Projects (as a 'nested table') in one column and the result set from Send