On a webpage for an alumni group, I'm trying to manage teams, and in the teams table, I have the fields: year, team_category(Football, etc), and members(MtoM). I'm trying to show on the first page a list of categories but only one per field entry. Clicking on the category button would lead to a list of teams filtered by said category and show year and members of the team. So my example below would just be Football, Cheearleading, chess. How to I group by category or any potentially better method?
import React, { useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { getTeams } from "../../../api/apiCalls";
const Teams = () => {
const [teams, setTeams] = useState([]);
useEffect(() => {
getTeams()
.then((response) => {
console.log(response.data);
setTeams(response.data);
})
.catch((error) => {
console.log(error.message);
});
}, []);
return (
<div className="">
<h1>
Teams
<hr />
</h1>
{teams.map((teams, index) => (
<div className="" border="" key={teams.id}>
<Link
className="btn btn-outline-dark btn-warning m-1"
to={`/dashboard/teams/${teams.category}/`}
>
{teams.category}
</Link>
</div>
))}
</div>
);
};
CodePudding user response:
You can use reduce to only include the category once
teams.reduce((previousValue, currentValue) => {
return previousValue.some((team) => team.category === currentValue.category)
? previousValue
: [...previousValue, currentValue];
}, []).map... your code here