1
votes

I'm stuck with trying to map an array to display components for each entry. Here's what I'm doing currently,

Here's my RankStore;

const RankStore = observable({
loading: false,
error: "",
rank: {} as RankInfo,

LoadRank() {
    this.loading = true;
    this.error = "";

    GetRankInfo()
    .then(action((json:any) => {
        this.rank = json.rankDetails;
        console.log(json)
        this.loading = false;
    }))
    .catch(action((error: any) => {
        this.error = error.message;
        this.loading = false;
    }));
}
});

export default RankStore;

In this observable RankStore I am loading the rank, which fetches from an API, and setting it to 'rank' which is an array of my model RankInfo, shown below;

interface RankInfo {
serviceNumber: string
capBadge: string
endDate: string
equivalentNatoRank: string
mainTrade: string
regtCorps: string
seniorityDate: string
actingPaidRank: string
startDate: string
substantiveRank: string
}

export default RankInfo;

Information received from the API looks like so; enter image description here

Ordinary, to display this in a component, I would make the component an observer and simply call {RankStore.rank.serviceNumber} which works for my other Stores but not for this one as the data is a array containing two items. I am trying to MAP each array to a component so for each array it shows a component such as <h1> {RankStore.rank.serviceNumber} </h1> in this case it would render two components showing the respective service Numbers.

In the past I have done this as so;

          {this.state.tickets.map((ticket) => (
            <text key={ticket.id} value={ticket.id}>
              {ticket.ticketApplication.firstName}{" "}
              {ticket.ticketApplication.lastName}
            </text>
      ))}

However, anytime I try to map {RankStore.rank} I always get 'MAP does not exist in 'rank''. What is the appropriate way to map arrays to components with MOBX?

1

1 Answers

0
votes

It seems that you are setting the rank field as an object initially, and after the API call, changing it to an array. When rank is an object, it doesn't have the map function property on it. So, instead of:

rank: {} as RankInfo

do this:

rank: [] as RankInfo[]

Initialize as an empty array of the RankInfo type.