Harry
Harry

Reputation: 93

How can I conditionally map multiple arrays with if statements after fetching an array of objects? (React)

This is all in Prescriptions.js

I am fetching a bunch of prescription drugs from my api.

const [drugs, setDrugs] = React.useState([]);
    
useEffect(() => {
    fetch('/api/drugs')
        .then(response => response.json())
        .then(json => setDrugs(json))
}, [drugs])

After that's done, I want to make a category array based on drug.class and render it down there. If that category already exists, then push the drug into it's category's array, if it doesn't, make a new array based on that category, push the drug into that array, and render it as shown.

</Select>
    <ListSubheader>Category 1</ListSubheader>
    <MenuItem value="valuehere">Option 1</MenuItem>
    <MenuItem value="valuehere">Option 2</MenuItem>
    <ListSubheader>Category 2</ListSubheader>
    <MenuItem value="valuehere">Option 3</MenuItem>
    <MenuItem value="valuehere">Option 4</MenuItem>
</Select>

I've been trying to get this done for days and I am stuck, would appreciate some help!

Upvotes: 2

Views: 298

Answers (2)

elMeroMero
elMeroMero

Reputation: 962

return categories.map(category => (
  <> 
    <ListSubheader>{category.name}</ListSubheader>
    {drugs.map(drug => drug.category === category.name ? 
      <MenuItem value={drug.value}>{drug.name}</MenuItem>
      : null
    )}
  </>
))

Upvotes: 1

tomfrio
tomfrio

Reputation: 1034

You want to parse your API's response to a structure that you can easily iterate over, and render UI elements for. How to do this exactly, depends on the structure of your response. lodash is very useful for this purpose.

Ie.:

import _ from 'lodash'

const [drugs, setDrugs] = useState([])    
useEffect(() => {
    fetch('/api/drugs')
        .then(response => response.json())
        .then(json => {
            // assume `json` now has the structure:
            // [{ class: 'fooClass', name: 'bar'}, { ... }]
            setDrugs(_.groupBy(json, 'class'))
            // `drugs` now has the structure:
            // { fooClass: [{...}] }
        })
}, [drugs])

// now we can iterate over the parsed groups:
return (
    <div>
        {_.map(drugs, (drugs, category) =>
            <div>
                <ListSubheader>{category}</ListSubheader>
                {_.map(drugs, drug => <MenuItem>{drug.name}</MenuItem>)}
            </div>
        )}
    </div>
)

Upvotes: 0

Related Questions