Home > Enterprise >  How to use map in react component using nextjs app?
How to use map in react component using nextjs app?

Time:01-29

I have data returned from the backend as an array that i want to populate on react component.

home.js

import Head from "next/head";
import Header from "../src/components/Header";
import * as React from 'react';
import { styled } from '@mui/material/styles';
import Box from '@mui/material/Box';
import Paper from '@mui/material/Paper';
import Grid from '@mui/material/Grid';
import TextField from '@mui/material/TextField';
import SendIcon from '@mui/icons-material/Send';
import Stack from '@mui/material/Stack';
import Button from '@mui/material/Button';
import getDupImages from "../src/services/getDupImages";
import { useState, useEffect } from 'react'

const Item = styled(Paper)(({ theme }) => ({
  backgroundColor: theme.palette.mode === 'dark' ? '#1A2027' : '#fff',
  ...theme.typography.body2,
  padding: theme.spacing(1),
  textAlign: 'center',
  color: theme.palette.text.secondary,
}));

export default function Home({data}) {
  let _data;
  const fetchData = async () => {
    _data = await getDupImages();
    console.log("DATA>>>", _data);
    return _data;
  };
   const submit = (event) => {
    event.preventDefault();
    fetchData();
   }
  return (
    <>
      <Head>
        <title>De-Dup</title>
        <link rel="icon" type="image/ico" href="/img/goals.ico" />
      </Head>
      <Header />
      <section>
      <Box sx={{ flexGrow: 1 }}>
      <Grid container spacing={2}>
        <Grid item xs={5}>
          <Box
              component="form"
               sx={{
                '& > :not(style)': { m: 1, width: '75ch' },
              }}
               noValidate
               autoComplete="off"
            >
            <TextField id="outlined-basic" label="location path" variant="outlined" />
            <Stack direction="row" spacing={2}>
            <Button variant="contained" onClick={submit} endIcon={<SendIcon />}>
              Submit
            </Button>
          </Stack>
        </Box>
        </Grid>
        <Grid item xs={7}>
        {data.map((d) => {
        return (
          <div>
            {d.title}
          </div>
        );
      })}
        </Grid>
      </Grid>
    </Box>
      </section>
    </>
  );
}

Error

1 of 1 unhandled error

Server Error
TypeError: Cannot read property 'map' of undefined

This error happened while generating the page. Any console logs will be displayed in the terminal window.

CodePudding user response:

Put the data in the component state and check if there actually is data before displaying it.

const [data, setData] = useState();
const fetchData = async () => {
   setData(await getDupImages());
}

Then in your JSX:

{!!data && data.map(d => <div>{d.title}</div>}

CodePudding user response:

You are trying to render the data before it is available. Use this instead

{data && data.map((d) => {
    return (
      <div>
        {d.title}
      </div>
    );
  })}

CodePudding user response:

Either initialise the data state as an array or use the Optional chaining (?.) operator before the map function:

data?.map((d) => {
  return <div>{d.title}</div>;
})

Hope this helps.

  • Related