Wanted to get some input into a little problem I encounted.
What I'm trying to do
Data is being fetched using a headless CMS. The green are buttons/links that will scroll down to the corresponding section/category.
The goal is to add an element whether it be an (h3 or a div with a rule) with the category title followed by all the items in that category.
If the category changes, category element should be added to the DOM with the corresponding name followed by all the items belonging to that category.
What I have tried
My first approach was to use an if statement
let data = results.map( (item, iterator, theArray) => {
let insertToHTML;
if(item.category !== theArray[i -1 ].category) {
insertToHTML = `<div class="category-name"> ${item.category} </div>`
}
return insertToHTML;
})
document.querySelector("#product-container").innerHTML = data;
This quickly became a bad option. If items are updated out of order you'll have a section created with just one or two items.. It could also be a duplicate of a pre existing category.
Moving forward
I'm sure there are other ways to do this. But I'm not familiar with a pattern for this yet
Another option i thought up was to have multiple ajax/fetch requests for each section, with the html for the sections hard coded but then this page won't be 100% dynamic... not good.
My last and final option is to query the cms by category and list all the products in that category, rather than fetching products and trying to list categories.
Appreciate any input