Home > other >  Make sure state is updated before rendering data in React Modal
Make sure state is updated before rendering data in React Modal

Time:10-19

I am using Material-UI component, useState hook and NextJS framework.

I am mapping someData in my render, the structure of a someData element is :

someData[i] : {
  "id": number,
  "name": string,
  "surname": string
}

My problem is to pass mapped data to Modal (specific to the mapped data).

{someData.map((data) => (
  <Grid item key={data.id}>
    <Card>
      <CardContent>
        <Typography>
          {data.surname} {data.name}'s card.
        </Typography>
      </CardContent>
      <Button
        onClick={() => {
          setModalData(data);
          setOpen(true);
        }}
      >
        Follow
      </Button>
      <Modal
        open={open}
        onClose={setOpen(false)}
      >
        <Box>
          <Typography>
            Follow {modalData.surname} ?
          </Typography>
          <Button onClick={() => handleFollowSubmit(modalData)}> 
               /*Function declared not important here*/
            Yes
          </Button>
        </Box>
      </Modal>
    </Card>
  </Grid>
))}

And the state used here are:

const [open, setOpen] = useState(false); // to handle the Modal opening
const [modalData, setModalData] = useState(null); // to pass Data to the modal

The idea is that you can't pass mapped data to a modal using the mapping, you have to use a State Hook to do so: When you open a modal, you pass the corresponding data through the State Hook.

But when I render the webpage I get this error :

TypeError: Cannot read properties of null (reading 'surname')

Pointing at modalData.surname

Any help would be appreciated!

CodePudding user response:

someData is an object not an array. No need to use the map operator

  <Grid item>
    <Card>
      <CardContent>
        <Typography>
          {someData.surname} {someData.name}'s card.
        </Typography>
      </CardContent>
       ....
    </Card>
  </Grid>
))}

CodePudding user response:

Just add !!modalData to its open prop?

 <Modal
  open={!!modalData && open}
  onClose={setOpen(false)}
/>
  • Related