-1

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.

3 Answers 3

2

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>}
Sign up to request clarification or add additional context in comments.

3 Comments

It seems to be a React Server Component, which means you can't use useState.
!! is not needed here. values are coerced to Boolean.
@damonholden some compiler settings (e.g. strictNullChecks in typescript) require explicit casting to boolean for falsy data. This is totally fine and acceptable code in some circumstances.
1

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

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

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.