Rodney Wormsbecher
Rodney Wormsbecher

Reputation: 927

React + axios async call

I am using axios to fetch some data on the componentDidMount lifecycle method. The call was originally in the same file and thus i could update this.setState({members}). however I wanted to abstract the logic into a serperate file to keep the code clean.

I split the logic into a new file and start using the axios async await pattern. hoewever it seems like React doesn't wait for my axios call to finish. I went throught the docs and several posts but I cannot seem to find the problem. any hints are appreciated!

PS: I used create react app as base and added the dns mock: https://github.com/hapijs/isemail/issues/26

Teamcard file

import React from "react";
import { Icon } from "office-ui-fabric-react/lib/Icon";
import { PrimaryButton } from "office-ui-fabric-react/lib/Button";
import TeamCardLogo from "./teamCardLogo/teamCardLogo";
import TeamCardPersona from "./teamCardPersona/teamCardPersona";
import { GetGroupMembers } from "../../HttpRepositories/graphRepository";

class TeamCard extends React.Component {
    state = {
        members: ""
    };

    componentDidMount() {
        let members = GetGroupMembers(this.props.id, 5);
        console.log("members", members);

        this.setState({ members });
    }

    render() {
        let members = "";

        if (
            typeof this.state.members !== "undefined" &&
            this.state.members.length > 0
        ) {
            members = this.state.members.map((member, i) => {
                return (
                    <div className="team-card-body__personas-wrapper-person" key={i}>
                        <TeamCardPersona
                            className="team-card-body__personas-wrapper-person"
                            member={member}
                            key={i}
                        />
                    </div>
                );
            });
        }
        let favouriteIcon = "";

        this.props.isFavorite === true
            ? (favouriteIcon = <Icon iconName="FavoriteStarFill" />)
            : (favouriteIcon = <Icon iconName="FavoriteStar" />);

        return (
            <article className="team-card-wrapper">
                <header className="team-card-wrapper__header">
                    <TeamCardLogo
                        className="team-card-wrapper__header-photo"
                        teamId={this.props.id}
                    />
                    <div className="team-card-wrapper__header-options-wrapper">
                        <div className="header-options__icon-group">
                            <div className="header-options__group-type">
                                <Icon iconName="LockSolid" />
                            </div>
                        </div>

                        <div className="header-options__icon-group">
                            <div className="header-options__favourite">{favouriteIcon}</div>
                        </div>
                    </div>
                </header>

                <section className="team-card-body">
                    <h1>{this.props.title}</h1>
                    <h2>Leden: {this.props.memberCount}</h2>

                    <div className="team-card-body__personas-wrapper">{members}</div>

                    <p className="description">{this.props.description}</p>

                    <div className="team-card-body__join-button-wrapper">
                        <PrimaryButton text="Lid worden" />
                    </div>
                </section>
            </article>
        );
    }
}

export default TeamCard;

seperated get request file:

import { getGraphToken } from "../adalConfig";
import axios from "axios";
import { resolve } from "dns";

export async function GetGroupMembers(groupId, numberOfMembers) {
    // we initiate a new token, to be sure that it didn't expire.

    let graphToken = getGraphToken();

    let response = await axios({
        url: `https://graph.microsoft.com/v1.0/groups/${groupId}/members?$top=${numberOfMembers}`,
        method: "GET",
        headers: { Authorization: "Bearer " + graphToken }
    });

    if (response.status != 200 && response.status != 204) {
        console.log("error");
    }

    console.log("returning data", response.data.value);
    return response.data.value;
}

Screenshot of logging: enter image description here

Upvotes: 0

Views: 437

Answers (1)

deniscapp
deniscapp

Reputation: 820

You are missing an await here: let members = await GetGroupMembers(this.props.id, 5); and componentDidMountmust be declared async.

Upvotes: 1

Related Questions