0

Tell me how to properly make such a function. I use javascript with the React framework

i am get from API this json array

  [{
      id: 0,
      credit: {
        id: 7
      }
      "another data"
    }]

I want to have a result at the end, like this

[{
      id: 0,
      credit: {
        id: 7,
        bank: "Bank Name X" // This parameter must also be obtained from the API
      }
      "another data"
    }]

i am try attach with this function

let fData;
let lData = [];

for (let i = 0; i < data.length; i++) {
  fData = {
    ...data[i],
    credit: {
      bank: axios.get("http://localhost:8080/api/v1/products/credits/" + data[i].credit.id)
        .then(function(result) {
          return result.data.partner.name;
        })
    }
  }
  lData.push(fData);
}

console.log(lData);

This code returns. How to get Bank Name X

credit:
bank: Promise
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: "Bank Name X"
6
  • Where and how do you use the returned data Commented Jun 11, 2020 at 11:48
  • next I show in render with map Commented Jun 11, 2020 at 11:49
  • And where are you fetching this data? In render method? Commented Jun 11, 2020 at 11:49
  • Can you please update the question with an example showing what you expect the end result to be? Commented Jun 11, 2020 at 11:50
  • variable data i am get from API Commented Jun 11, 2020 at 11:50

2 Answers 2

1

You can do something like that in your React component when you want to fetch some data from API.

import React from 'react';
import axios from 'axios';

export default class Bank extends React.Component {
    state = {
        data: []
    }

    componentDidMount() {
        axios.get(`http://localhost:8080/api/v1/products/credits/`)
          .then(res => {
            this.setState({ data: res });
        })
    }

   render() {
       return (
         <ul>
          {this.state.data.map(d => <li>{d.credit.bank.name}</li>)}
        </ul>
      )
   }

}

Sign up to request clarification or add additional context in comments.

Comments

1

This solution for me ) Thank's ru.stackoverflow

let fData;
let lData  = [];
let pData = [];


        for(let i = 0; i < data.length; i ++){
            pdata.push(axios.get("http://localhost:8080/api/v1/products/credits/" + data[i].credit.id))
            fData = {
                ...data[i],
                credit: {
                  bank: "blank"

                }
            }
           lData.push(fData);
        }

Promise.all(pData).then(function(result){
    for(var res in result){
        lData[res].credit.bank = result[res].data.partner.name);
    }
    console.log(lData)
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.