alvinfungg
alvinfungg

Reputation: 27

How to map an array inside an array in UseEffect

Below image will be the response I get from useEffect

enter image description here

My useEffect will look like this:

useEffect(() => {

    const getStatesData = async () => {
      await fetch ('http://localhost:3001/covid19')
      .then((response) => response.json())
      .then((data) => {
        const dataStates = data.states
        const states = dataStates.map((state2) => (
          {
            name: state2.name,
            total: state2.total
          }
        ));
          setStates(states)
      })
    }

    getStatesData();
  }, []);

I'm trying to get name and total inside districts, how can I do that?

I've tried using adding districts: state2.districts in useEffect, and adding {state.districts.map(({name, total}) => ({name} ))} directly in the <div> but it's returning an error: Error: Objects are not valid as a React child (found: object with keys {name}). If you meant to render a collection of children, use an array instead.


I'm currently using material-ui to help me get thigs easier, here is my full code excluding the useEffect:

<div className="App">
      {states.map(state => (
            <Accordion expanded={expanded === state.name}
            <AccordionSummary
              expandIcon={<ExpandMoreIcon />}
              aria-controls="panel1bh-content"
              id="panel1bh-header"
            >
              <Typography className={classes.heading}>{state.name} ({state.total}) </Typography>
            </AccordionSummary>
            <AccordionDetails>
              <Typography>
              
               !! DISTRICTS NAME HERE (DISTRICTS TOTAL HERE) !!

              </Typography>
            </AccordionDetails>
          </Accordion>
          ))}
    </div>

Upvotes: 1

Views: 166

Answers (1)

Charchit Kapoor
Charchit Kapoor

Reputation: 9284

Instead of mapping districts like this:

{state.districts.map(({name, total}) => ({name} ))}

do it like this:

{state.districts.map(({name, total}) => `${name} (${total})`)}

or even better to a component like this:

{state.districts.map(({name, total}) => <div>{name} ({total})<div>)}

within the Typography component.

The reason being, the mapping state.districts.map(({name, total}) => ({name} )) returns an object for each district, and React doesn't recognizes objects as renderable components.

Upvotes: 1

Related Questions