This is all in Prescriptions.js
I am fetching a bunch of prescription drugs from my api.
JavaScript
x
8
1
const [drugs, setDrugs] = React.useState([]);
2
3
useEffect(() => {
4
fetch('/api/drugs')
5
.then(response => response.json())
6
.then(json => setDrugs(json))
7
}, [drugs])
8
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.
JavaScript
1
9
1
</Select>
2
<ListSubheader>Category 1</ListSubheader>
3
<MenuItem value="valuehere">Option 1</MenuItem>
4
<MenuItem value="valuehere">Option 2</MenuItem>
5
<ListSubheader>Category 2</ListSubheader>
6
<MenuItem value="valuehere">Option 3</MenuItem>
7
<MenuItem value="valuehere">Option 4</MenuItem>
8
</Select>
9
I’ve been trying to get this done for days and I am stuck, would appreciate some help!
Advertisement
Answer
JavaScript
1
10
10
1
return categories.map(category => (
2
<>
3
<ListSubheader>{category.name}</ListSubheader>
4
{drugs.map(drug => drug.category === category.name ?
5
<MenuItem value={drug.value}>{drug.name}</MenuItem>
6
: null
7
)}
8
</>
9
))
10