-1

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

tan shi yu
  • 303
  • 1
  • 7
  • 1
    `forEach` doesn't return anything, so `groupsDisplay` will be `undefined`. What you want is `.map()`, ensure you `return` from your callback if your giving your arrow function a body. – Nick Parsons Jun 07 '23 at 13:13
  • 1
    @NickParsons Thank you, that has solved my problem haha, I didnt expect to make 2 errors here ( forEach and the lack of return since im using { } ). Thanks so much! – tan shi yu Jun 07 '23 at 13:16

2 Answers2

2

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

const groupsDisplay = groupsData.map((group) => <Group key={group._id} />)
lluchkaa
  • 151
  • 4
0

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.

Taron Qalashyan
  • 660
  • 4
  • 8