skip to Main Content

my code is seen below

import React, { useEffect, useState } from 'react';
import { Box } from '@mui/system';
import { Link, Outlet } from 'react-router-dom';
import { Button } from '@mui/material';
import axios from 'axios';
import Group from './Group';


const Groups = () => {

  const [groupsData, setGroupsData] = useState([]);

  useEffect(() => {
    axios.get('/api/group/getGroups')
      .then(res => setGroupsData(res.data))
  }, [])

  console.log(groupsData)

  const groupsDisplay = groupsData.forEach((group) => {
    <Group key={group._id} />
  })

  

  return (
    <Box>
      <Button component={Link} to="./createGroup" variant="contained">
        Button Press
      </Button>
      <Group />
      {groupsDisplay}
      <Outlet />
    </Box>
  )
}

export default Groups

After I used useEffect to fetch the data from my database, although the console.log(groupsData) did indicate that there is data, the groupsDisplay does not reflect this change on my DOM. May I know if there is anything I can do to change that? Thank you! Below is a picture of the console.log and my current DOM. The group on the screen is the above the {groupsDisplay}, thank you.

enter image description here

2

Answers


  1. You should use .map, not .forEach to convert state to elements.

    const groupsDisplay = groupsData.map((group) => <Group key={group._id} />)
    
    Login or Signup to reply.
  2. The issue lies in the groupsDisplay variable. Currently, you are using the forEach method, which does not return anything. Instead, you should use the map method to create an array of JSX elements.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search