Home > Blockchain >  Mapping An Array In React JS not rendering
Mapping An Array In React JS not rendering

Time:02-25

I have a nested dictionary object called teams which I preprocess into an array of arrays.

Initially, my teams data (the nested array) looks like this:

enter image description here

and then it is processed into a teamCards array which looks like this:

enter image description here

However even once processed, my map function is still not mapping my array into a component like I would like. Does anyone know why not? Here is my react code:

import React, {useEffect} from 'react'
import { Grid } from '@material-ui/core'
import TeamCard from './TeamCard'
import loader from '../images/loader.gif'

export default function Teams({teamsLoading, teams}) {
    console.log(teams)

    const teamCards = []

    function populateTeamCards() {
        Object.keys(teams).forEach(function(key) {
            Object.keys(teams).forEach(function(key) {
                Object.keys(teams[key]).forEach(function(t) {
                    teamCards.push([t, teams[key][t]])
                })
            })
        })
    }

    useEffect(() => {
        if (teamsLoading == false) {
            populateTeamCards()
        }
    }, [teamsLoading])

    return (
            teamsLoading ?
            <img src={loader} alt="loading..." /> :
            <Grid>
                {teamCards.map((element, index) => {
                    return (
                        <TeamCard
                            key={index}
                            teamName={element[0]}
                        />
                    )
                })}
            </Grid>
    )
}

CodePudding user response:

You can try this

import React, { useEffect, useState } from "react";
import { Grid } from "@material-ui/core";
import TeamCard from "./TeamCard";
import loader from "../images/loader.gif";

export default function Teams({ teamsLoading, teams }) {
  const [teamCards, setTeamCards] = useState([]);

  function populateTeamCards() {
    let newArray = [];

    Object.keys(teams).forEach(function (key) {
      Object.keys(teams[key]).forEach(function (t) {
        newArray.push([t, teams[key][t]]);
      });
    });

    setTeamCards(newArray);
  }

  useEffect(() => {
    if (teamsLoading == false) {
      populateTeamCards();
    }
  }, [teamsLoading]);

  return teamsLoading ? (
    <img src={loader} alt="loading..." />
  ) : (
    <Grid>
      {teamCards.map((element, index) => {
        return <TeamCard key={index} teamName={element[0]} />;
      })}
    </Grid>
  );
}

CodePudding user response:

You're setting an instance variable's value and this does not trigger a component re-render, which means even after teamCards is updated, the UI still stays the same as when it was empty.

What you need is to use a React state like this:

const [teamCards, setTeamCards] = useState([]);
...

const cards = [];
// ... push to cards ...
setTeamCards(cards);
  • Related