1

I have this object, i want to fecth all url.

Object {
  "Info": "/api/2",
  "Logo": "/api/2/Logo",
  "Photo": "/api/2/photo",
}

I want to store the response in a state, like in the example below, I can't know the keys of the object, but no matter what key is the response is organized with that key

Data
[
   "Info": 
       ['API RESULTS'],
   "Logo": 
       ['API RESULTS'],
   "Photo": 
       ['API RESULTS']
]

I made the promise like this

     await Promise.all(Object.values(RequestURL).map(Url => 
     {
         fetch(`${this.state.URL}${Url}`)
         .then(Res => Res.json())
         .then(Res => this.setState({Data: [...this.state.Data, Res.Data] }))
         .catch(Err => this.setState({ IsLoading: false, IsError: true}))
      }))

but I don't have the result in the format I want because I only store the data in an array, not an object with the key-value

this.setState({Data: [...this.state.Data, Res.Data] }))

the response I got is

Array [
  Array [
    Object {
        "API_DATA"
    }

and i want something like this

Array [
  Info: [
    Object {
        "API_DATA"
    }
  Logo: [
    Object {
        "API_DATA"
    }

2 Answers 2

2

With Object.entries() you could pass both the key and the value of each object entry into the map function. Then wait for the response to finish and return a new array with the key and the returned data as a pair.

In the map loop don't forget to return the result of the request, otherwise there is nothing to use Promise.all() on.

After all responses are in you can turn this array of arrays back into an object with Object.fromEntries(), reversing the effect.

To demonstrate how it works I've made an example with the Star Wars API to perform dummy requests.

const endpoints = {
  "Info": "people/1/",
  "Logo": "planets/2/",
  "Photo": "starships/9/",
};

const responses = Object.entries(endpoints).map(async ([ key, url ]) => {
  try {
    const response = await fetch(`https://swapi.dev/api/${url}`);
    const data = await response.json();
    return [ key, data ];
  } catch (error) {
    console.log(error);
  }
});

Promise.all(responses)
  .then(results => Object.fromEntries(results))
  .then(console.log);

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

1 Comment

thanks men, in my case i store the result in the state like this .then(Res => this.setState({Data: Res}));
1

Change your loop slightly to use Object.keys instead of Object.values so that you can get both the keys and values.

Simplified version:

const obj = {
  Info: "/api/2",
  Logo: "/api/2/Logo",
  Photo: "/api/2/photo",
}

Object.keys(obj).map((key) => {
  console.log('key', key);
  console.log('value', obj[key]);
})

Then set your state with a dynamic property like this:

this.setState({ [key]: yourData })

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.