I have a label
, which has onClick
callback:
<label className="cursor-pointer" onClick={loadExisting}>
Click me
</label>
loadExisting
function, fetch
'es data from api, and passses it to parseData
function.
const loadExisting = () => {
fetch("/api/v.1.0/events", { mode: "no-cors" })
.then(function(response) {
if (!response.ok) {
console.log("Something is wrong");
return;
}
return response.json();
})
.then(data => {
if (!data) {
return;
}
parseEvents(data);
});
};
In this function, I am trying to store only those events, which's title
s are unique:
const parseEvents = data => {
if (data) {
for (let i = 0; i < data.length; i++) {
if (titlesArray.indexOf(data[i].title) < 0) {
setTitlesArray([...titlesArray, data[i].title]);
setEvents([...events, data[i]]);
}
}
}
};
Basically my idea is to set all the unique titles into titlesArray
and if event's title
is unique, I add it to both titlesArray
and events
.
Problem: This only works if I keep clicking on that label
. With first click events.length
is equal to 0, second click- equal to 1, third click- equal to 2, etc. Why it does not parse all events at once? So after 1 click I would have ~10 events that have unique titles.