vjeko
vjeko

Reputation: 47

Object keys iteration issue

I've got this API call to marvel and I am exporting it and saving as a state in React.

 avengers.map((avenger, index) => {
  const url = `
    http://gateway.marvel.com/v1/public/characters/${avenger}?ts=${ts}&apikey=${publicKey}&hash=${hash}
  `
  fetchMarvelData(url, index)
})

let fetchedData = {}

async function fetchMarvelData (url, index) {
  const response = await fetch(url, {
    headers: {
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  })
  const data = await response.json()
  fetchedData[`avenger${index}`] = data.data.results[0]
}

export default fetchedData

When I try to iterate Object.keys(fetchedData) I get an empty array. Not quite sure what is wrong here, any help is appreciated.

React state log

EDIT: Clarified what I am trying to iterate over.

EDIT: Added image of React state console.log

Upvotes: 1

Views: 69

Answers (2)

jjjjjjjjjjjjjjjjjjjj
jjjjjjjjjjjjjjjjjjjj

Reputation: 3118

That's because you're exporting an empty object. Since you're doing asynchronous calls that you aren't awaiting, fetchedData will just be an empty object at the time of export.

If you want all the requests to finish before, you could do something like this:

const hash         = '...'; // Replace
const ts           = '...'; // Replace
const publicKey    = '...'; // Replace
const fetchOptions = {
  headers: {
    'Content-Type': 'application/json',
    'Accept': 'application/json'
  }
};

const fetchAvenger = async avenger => {
  const url      = `http://gateway.marvel.com/v1/public/characters/${avenger}?ts=${ts}&apikey=${publicKey}&hash=${hash}`;
  const response = await fetch(url, fetchOptions);
  const data     = await response.json();

  return data.data.results[0];
};

const fetchAvengers = async avengers => {
  const remoteAvengers = [];
  await Promise.all(avengers.map(async avenger => {
    const remoteAvenger = await fetchAvenger(avenger);
    remoteAvengers.push(remoteAvenger);
  }));
  return remoteAvengers;
};

export default fetchAvengers;

And then in your component you could add the the avengers to state like so:

import fetchAvengers from 'path/to/fetchAvengers';
// ...

// Show a loader or something?
this.setState({ isFetchingAvengers: true });

// Waits for all avengers to be fetched from api
const avengers = await fetchAvengers([...]);

// Update state, hide loader
this.setState({ avengers, isFetchingAvengers: false });

I haven't tested the code so there might be some errors in it, let me know and I'll try to help.

Upvotes: 1

Wathsala Abeykoon
Wathsala Abeykoon

Reputation: 51

According to your console out put given above. There is an empty object at top with no props in it.

Upvotes: 0

Related Questions