I have react component with a array of a shoppinglist in state.
The shoppinglist have multiple arrays and object to reflect which ingredients matches each day and meal.
This functions loops through each ingredient push it to an empty array which I later maps over and returns the value. When I find an ingredient which already exists in the ingredient-array, then it modifies the value instead of pushing a new similar ingredient. (the reason for this is that a breakfast on monday and tuesday can both have the ingredient "apple", and then I just want to show "apple" in the list once, but have the amount of values to reflect both breakfasts.
The problem:
The value of the ingredient I modify is changed on state-level. Which means when I run the function again (I do because the user can filter days) the value increases.
Scenario
Breakfast in both monday and tuesday has the ingredient Apple. Apple has a value of 2, since the recipe needs two apple. This means my loop should return 4 apples. And it does the first time. But when I change som filters so the loops run again to reflect the new filter, it now shows 6 apples.
Can someone tell me how this is possible? How can this code modify my global state?
loopIngredients (items) {
const ingredients = []
const newArr = items.slice()
newArr.map((data, key) => {
data.map((data, index) => {
const valid = ingredients.find((item) => item.ingredient.id === data.ingredient.id)
if (valid) {
const parentValue = parseInt(ingredients[index].value)
const localValue = parseInt(data.value)
ingredients[index].value = (parentValue + localValue).toString()
} else {
ingredients.push(data)
}
})
})
} // END loopIngredients
Found the solution:
The ingredients.push(data) pushed the reference from the state.
I thought I removed the reference by doing .slice(), but apparently not.
By doing ingredients.push(Object.create(data)) it worked as intended.
Related
I'm trying to add a list inside a state using the set method, but my state remains empty
App.js
// Starts the screts word game
const startGame = () => {
// pick word and pick category
const { word, category } = pickWordAndCategory();
// create array of letters
let wordLetters = word.split("");
wordLetters = wordLetters.map((l) => l.toLowerCase());
// Fill states
setPickedCategory(category);
setPickedWord(word);
setLettersList(wordLetters);
console.log('wordLetters', wordLetters);
console.log('lettersList', lettersList);
setGameState(stages[1].name);
};
const pickWordAndCategory = () => {
// pick a random category
const categories = Object.keys(words);
const category = categories[Math.floor(Math.random() * Object.keys(categories).length)];
console.log('category', category);
// pick a random word
const word = words[category][Math.floor(Math.random() * words[category].length)]
console.log(word);
return { word, category };
}
Here is the browser log
When looking at the log we find our state empty
When you use setLettersList(...), you are not actually changing lettersList variable itself. Notice how when you declare it, const [lettersList, setLettersList] = useState([]); letterList is actually constant, so that variable can't even be changed. Instead, it tells React to rerun the function component, this time giving lettersList the new value. Therefore, for the updated value, it will only come once const [lettersList, setLettersList] = useState([]); is rerun again from the entire function being rerun again.
If you want to monitor changes to lettersList, you can do:
useEffect(() => {
console.log(lettersList);
}, [lettersList]);
This will print lettersList every time it is updated.
States updates are asynchronous, so when you set a new state value and console.log() right after it, it's going to show the previous value, because the state hasn't been updated yet.
That's why your lettersList value show the old value of the state in the console (empty array).
I want to retrieve a list of products in relation to the user's position, for this I use Geofirestore and update my Flatlist
When I have my first 10 closest collections, I loop to have each of the sub-collections.
I manage to update my state well, but every time my collection is modified somewhere else, instead of updating my list, it duplicates me the object that has been modified and adds it (updated) at the end of my list and keep the old object in that list too.
For example:
const listListeningEvents = {
A: {Albert, Ducon}
B: {Mickael}
}
Another user modified 'A' and delete 'Ducon', I will get:
const listListeningEvents = {
A: {Albert, Ducon},
B: {Mickael},
A: {Albert}
}
And not:
const listListeningEvents = {
A: {Albert},
B: {Mickael},
}
That's my useEffect:
useEffect(() => {
let geoSubscriber;
let productsSubscriber;
// 1. getting user's location
getUserLocation()
// 2. then calling geoSubscriber to get the 10 nearest collections
.then((location) => geoSubscriber(location.coords))
.catch((e) => {
throw new Error(e.message);
});
//Here
geoSubscriber = async (coords) => {
let nearbyGeocollections = await geocollection
.limit(10)
.near({
center: new firestore.GeoPoint(coords.latitude, coords.longitude),
radius: 50,
})
.get();
// Empty array for loop
let nearbyUsers = [];
// 3. Getting Subcollections by looping onto the 10 collections queried by Geofirestore
productsSubscriber = await nearbyGeocollections.forEach((geo) => {
if (geo.id !== user.uid) {
firestore()
.collection("PRODUCTS")
.doc(geo.id)
.collection("USER_PRODUCTS")
.orderBy("createdDate", "desc")
.onSnapshot((product) => {
// 4. Pushing each result (and I guess the issue is here!)
nearbyUsers.push({
id: product.docs[0].id.toString(),
products: product.docs,
});
});
}
});
setLoading(false);
// 4. Setting my state which will be used within my Flatlist
setListOfProducts(nearbyUsers);
};
return () => {
if (geoSubscriber && productsSubscriber) {
geoSubscriber.remove();
productsSubscriber.remove();
}
};
}, []);
I've been struggling since ages to make this works properly and I'm going crazy.
So I'm dreaming about 2 things :
Be able to update my state without duplicating modified objects.
(Bonus) Find a way to get the 10 next nearest points when I scroll down onto my Flatlist.
In my opinion the problem is with type of nearbyUsers. It is initialized as Array =[] and when you push other object to it just add new item to at the end (array reference).
In this situation Array is not very convenient as to achieve the goal there is a need to check every existing item in the Array and find if you find one with proper id update it.
I think in this situation most convenient will be Map (Map reference). The Map indexes by the key so it is possible to just get particular value without searching it.
I will try to adjust it to presented code (not all lines, just changes):
Change type of object used to map where key is id and value is products:
let nearbyUsersMap = new Map();
Use set method instead of push to update products with particular key:
nearbyUsersMap.set(product.docs[0].id.toString(), product.docs);
Finally covert Map to Array to achieve the same object to use in further code (taken from here):
let nearbyUsers = Array.from(nearbyUsersMap, ([id, products]) => ({ id, products }));
setListOfProducts(nearbyUsers);
This should work, but I do not have any playground to test it. If you get any errors just try to resolve them. I am not very familiar with the geofirestore so I cannot help you more. For sure there are tones of other ways to achieve the goal, however this should work in the presented code and there are just few changes.
The goal is to filter an array based on the slots the user has selected.
For example an array has slots for 7pm-9pm,10pm-12pm and so on.
Now the user selects 7pm-9pm, so now I want to filter the array which have 7ppm-9pm or is the users wants
7pm-9pm and 10pm-11pm so the data should be based on 7pm-9pm and 10pm-11pm
Here is how I store the values
This is the original array
data :[
{
name:"something",
phone:"another",
extraDetails : {
// some more data
slots : [
{item:"6PM-7PM"},
{item:"7PM-8pm}
]
}
},{
// Similarly more array with similar data but somewhere slots might be null
}
]
Now for example we have this array
slots:[{6PM-7PM,9PM-10PM,11PM-12AM}]
Now this should filter all those which includes timeslots of 6PM-7PM,9PM-10PM,11PM-12AM
or if the user selects
slots:[{6PM-7PM}]
We should still get the results that includes 6pm-7pm more or else don't matter.
First, I'd suggest using this for your slots representation for simplicity, but you can alter this approach depending on your actual code:
slots: ['6PM-7PM', '9PM-10PM', '11PM-12PM']
Then you can iterate through your data and use filter:
const querySlots = ['6PM-7PM', '9PM-10PM', '11PM-12PM'];
const matchedPersonsWithSlots = data.filter( (person) => {
let i = 0;
while ( i < person.extraDetails.slots.length ) {
if (querySlots.includes(person.extraDetails.slots[i]) return true;
i += 1;
}
return false;
});
matchedPersonsWithSlots will then have all the people that have a slot that matches one of the slots in your query, because if any of the query slots are in a person's list of slots, then it's included in the result set.
EDIT to include a different use case
If, however, every slot in the query array must be matched, then the filtering has to be done differently, but with even less code.
const matchedPersonsWithAllSlots = data.filter(person =>
querySlots.every((qSlot)=>person.extraDetails.slots.includes(qSlot)));
The above will go through each person in your data, and for each of them, determine whether the person has all of your query slots, and include them in the result list, only if this is true.
I built a custom component that filters an array of objects. The filter uses buttons, sets from active to non-active and allows more than one option on/off at the same time.
StackBlitz of my attempt - https://stackblitz.com/edit/timeline-angular-7-ut6fxu
In my demo you will see 3 buttons/options of north, south and east. By clicking on one you make it active and the result should include or exclude a matching "location" either north, south and east.
I have created my methods and structure to do the filtering, I'm struggling with the final piece of logic.
So far I have created a method to create an array of filtered locations depending on what the user clicks from the 3 buttons.
Next this passes to my "filter array" that gets the logic that should compare this filtered array against the original to bring back the array of results that are still remaining.
Its not quite working and not sure why - I originally got this piece of functionality working by using a pipe, but fore reasons do not want to go in that direction.
//the action
toggle(location) {
let indexLocation = this.filteredLocations.indexOf(location);
if (indexLocation >= 0) {
this.filteredLocations = this.filteredLocations.filter(
i => i !== location
);
} else {
this.filteredLocations.push({ location });
}
this.filterTimeLine();
}
// the filter
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
//the logic
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
https://stackblitz.com/edit/timeline-angular-7-ut6fxu
Sorry for my expression but u have a disaster in your code. jajaja!. maybe u lost that what u need but the logic in your functions in so wrong. comparing string with objects. filter a array that filter the same array inside... soo u need make a few changes.
One:
this.filteredLocations.push({location});
Your are pushing object. u need push only the string.
this.filteredLocations.push(location);
Two:
filterTimeLine() {
this.filteredTimeline = this.timeLine.filter(x =>
this.contactMethodFilter(x)
);
}
in this function you filter the timeLine array. and inside of contactMethodFilter you call filter method to timeLine again....
See a functional solution:
https://stackblitz.com/edit/timeline-angular-7-rg7k3j
private contactMethodFilter(entry) {
const myArrayFiltered = this.timeLine.filter(el => {
return this.filteredLocations.some(f => {
return f.location === el.location;
});
});
}
This function is not returning any value and is passed to the .filter
Consider returning a boolean based on your logic. Currently the filter gets undefined(falsy) and everything would be filtered out
So, I'm a bit stuck. I'm filtering an array based on the values of another array. When the user clicks a check box a year value gets pushed to an array (checkedBoxes), then the yearMarker array is populated from meeting the condition IF the marker.year (from mapMarkers array) entry is equal to any value in the CheckedBoxes array. This then gets passed to the getMarkers function which populates the map I'm working on. This all works perfectly. However when I click uncheck the box it doesn't work. If I log the checkedBoxes array I can see that the year is being removed as it should. The code to populate/replace yearMarkers is the same as the checked state, as with the function to create map markers. Yet it doesn't work. Any help to straighten out my thinking on this would be appreciated.
subFilter.forEach(item => {
const elm = item;
item.addEventListener('click', function () {
if (elm.checked) {
markersLayer.clearLayers();
checkedBoxes.push(elm.value);
yearMarkers = mapMarkers.filter(marker => checkedBoxes.includes(marker.year));
getMarkers(yearMarkers, markersLayer);
} else{
checkedBoxes = checkedBoxes.filter(entry => entry !== elm.value);
yearMarkers = mapMarkers.filter(marker => checkedBoxes.includes(marker.year));
getMarkers(yearMarkers, markersLayer);
console.log('unchecked');
console.log(checkedBoxes);
}
})