DrummerGenius
DrummerGenius

Reputation: 545

Pushing responses of axios request into array

I have been pounding my head against this problem, and need help with a solution. I have an array of IDs within a JSON, and I am iterating over that array and making a GET request of each ID. I want to then push the response of those GET requests into an array.

Here is the function I am using to push the registrations into the array. It is iterating through an array of IDs:

getRegistrations = async (event) => {
    let registrations = [];

    await event.registrations.forEach(registration => axios.get('/event/getRegistration', {
        params: {
            id: registration
        }
    }).then(res => {
            registrations.push(res.data.properties)
        }
    ).catch(err => console.log(err)));
    return registrations;
};

Here is where I am calling that code:

render() {
    let event = this.getEvent();
    let registrations2 = [{
        age: 19,
        bio: 'test',
        firstName: 'hello',
        lastName: 'bye',
        password: 'adadas',
        telephone: "4920210213"
    }];
    if (this.props.listOfEvents.events.length !== 0 && !this.props.listOfEvents.gettingList && event) { //check if the array is empty and list has not been rendered yet
        let columns = [];
        let registrations = this.getRegistrations(event);
        console.log(registrations);
        let eventProperties = event.properties[0];
        Object.keys(eventProperties).forEach(key => columns.push({
            title: eventProperties[key].title,
            dataIndex: key,
            key: key
        }));
        console.log(registrations);
        console.log(registrations2);
        return (
            <h1>hi</h1>
        )
    }
    return <Loading/>
}

When I console-log 'registrations' vs 'registrations2' they should be very identical. However, in the javascript console on Google Chrome, 'registrations appears as '[]' where 'registrations2' appears as '[{...}]'.

I know that it is an issue related to promises (I am returning the registrations array before actually pushing) but I have no idea how to fix it! Some friendly help would be very much appreciated!

Upvotes: 1

Views: 8781

Answers (3)

Kyaw Kyaw Soe
Kyaw Kyaw Soe

Reputation: 3360

I recommend Promise.all, it will resolve single Promise after all promises have resolved. And technically async function is also promise so it will return promise.

here the example.

https://codesandbox.io/s/jzz1ko5l73?fontsize=14

Upvotes: 1

Prithviraj Sahu
Prithviraj Sahu

Reputation: 214

Since getRegistrations(event) returns a promise, you should perform operations on its return value inside then.

Instead of

let registrations = this.getRegistrations(event);
console.log(registrations);

Do this

this.getRegistrations(event).then(registrations => {
  console.log(registrations);
  // other operations on registrations
});

Upvotes: 0

Amol B Jamkar
Amol B Jamkar

Reputation: 1257

You need to use componentDidMount()lifecycle method for proper execution and state to store the data.

constructor (props) {
   super(props);
   this.state = {registrations :[]}
}
componentDidMount () {
    let response = this.getRegistrations()
    this.setState({registrations : response});
}

Then access that state in render method. It's not good practice to call api from render mothod.

Upvotes: 0

Related Questions