How would I go about deleting a single item in Firebase? - javascript

How would I go about deleting just a single item?
Provided I know the 'name' value ("To add") but I don't know the item ID value (-M0qUq...).
The following code works to delete the item, but I want to make it dynamic and not have to hardcode in the ID value.
handleRemove = (item) => {
db.ref('/items/-M0qUPNnHRbZAb1R3690/').remove();
}

Try the following:
let query = db.ref('items').orderByChild("name").equalTo("To add");
db.once('value').then((snapshot) => {
snapshot.forEach((subSnapshot) => {
let key = subSnapshot.key;
db.ref('items').child(key).remove();
});
});
First add a query equalTo, then iterate inside the returned result to be able to retrieve the key and then use remove() to delete.

Related

'splice' instead of 'filter'

I have a field for entering tags. It is also possible to remove tags.
And here I have a question.
My deletion code is below. Tags can be deleted one at a time, in any order (first, last, somewhere in the middle, it doesn't matter).
const deleteTag = (index) => {
setTags((prevState) => prevState.filter((tag, i) => i !== index));
};
But I would like to use 'splice' instead of 'filter'. With the same functionality.
Tell me how to do it
Splice's first argument is the item index, and the second argument is how many items you want to delete from that index.
const deleteTag = (index) => {
setTags((prevState) => {
prevState.splice(index, 1)
return [...prevState]
});
};
UPDATE
If you are using <StrictMode> the setState will execute twice and will delete two items instead of one.

first element is not pushing inside empty array in reactJS?

trying to push data coming to "id" to "selectedUserId" array, but first element is not inserting.
selectedUserId array does not contain first pushed element, push is only working from second element onwards.
const handleSelectOne=(e)=>{
const id = e.target.value;
console.log(id,"handling")
if(!selectedUserIds.includes(id))
{
selectedUserIds.push(id)
}
else
{
selectedUserIds.pop(id)
}
setCheckedStatusOne(!checkedStatusOne[id])
}
const handleDeleteSelectedClick=() =>{
let deletionItemsNo = selectedUserIds.length
selectedUserIds.map((id)=>{
return console.log(id, "<== element inside selecteduserids array")
})
console.log(deletionItemsNo, "<== number of elements in array")
}
output
console output
.pop() method doesn't accept any arguments. It used for removing the last array item.
To be able to insert element in the beginning you should use .unshift(id)

UseState how to set an Array back to empty?

I'm trying set clickFavIconArray back to an empty array with the hook.
Basically, the setClickFavIconArray has a list of IDs the showFavIcon() checks that ID and if it contains the same ID I want to remove it from the array and update the setClickFavIconArray to the new Array.
However, it just seems to be adding on to the original clickFavIconArray no matter what. Is there a way to clear the clickFavIconArray state back to an [] empty array?
Some help here would be awesome.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item))
setClickFavIconArray(newArray)
}
setClickFavIconArray([...clickFavIconArray, id])
}
Simply pass the new value of empty array to setClickFavIconArray():
setClickFavIconArray([])
To make sure that the id is not immediately added to the array again, add a return statement inside the if-statement.
const [clickFavIconArray, setClickFavIconArray] = useState([]);
function showFavIcon(id){
if (clickFavIconArray.includes(id)) {
const newArray = clickFavIconArray.filter(item => !id.includes(item));
setClickFavIconArray(newArray);
return; // make sure that the next line is not executed
}
setClickFavIconArray([...clickFavIconArray, id])
}
There are two issues with the code
filter function seems to be invalid it should be replaced with
clickFavIconArray.filter(item => id != item)
You are adding id again to the array with this
setClickFavIconArray([...clickFavIconArray, id])
If you want to remove id, there is no need for this line in your code.
However you can always set clickFavIconArray to an empty array state using this code:
setClickFavIconArray([])

unable to remove an object from localStorage using its id

function removeLocalStorageHelper(item, pizzaId) {
console.log(item.productID);
console.log(pizzaId);
if (item.productID == pizzaId) {
console.log("Working fine");
localStorage.removeItem(item);
console.log(localStorage);
}
}
function removeFromLocalStorage(pizzaId) {
var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
var cartRowContents = locStore.map((item) =>
removeLocalStorageHelper(item, pizzaId)
);
}
Whenever the user clicks on "Remove" button, removeFromLocalStorage() function is called which receives a number type variable pizzaId. Now, this pizzaId is stored in the localStorage and I want to remove the object associated with this pizzaId from my localStorage.
CONSOLE OUTPUT
Please help me to remove an object from localStorage using productID.
You can't directly remove an item from the stored array. For that you need to remove the intended element from array and insert again to localStorage like below. Otherwise it'll remove complete list from localStorage.
Note: You need to do the same wile adding new item to the localStorage.
function removeFromLocalStorage(pizzaId) {
var locStore = JSON.parse(localStorage.getItem("selectedProduct"));
var cartRowContents = locStore.filter((item) => item.productID !== pizzaId);
localStorage.setItem("selectedProduct", JSON.stringify(cartRowContents))
}
As I reivew your code, I see that you are retrieving the item from localStorage like this localStorage.getItem("selectedProduct") The question here is do you want to remove the entire locStore or just a part of it. Maybe locStore is a complex collection (array) from multiple products and not a single entity as this code hints
var cartRowContents = locStore.map((item) =>
removeLocalStorageHelper(item, pizzaId));
If this is the case you need to do something like this
var locStore = locStore.filter(function(item, index){
return item.productID != pizzaId;
});
Now you have a locStore collection without the item you want to remove and you have to save it back to localStorage like this
localStorage.setItem('selectedProduct', JSON.stringify(locStore));
Essentially you are overriding the old selectedProduct value in localStorage with a new one that does not contain the removed product.
If for some reason locStore is just a simple JSON object that you want to remove you can do this to delete it from localStorage
localStorage.removeItem('selectedProduct')
Well, if you just need to remove the selectedProduct, you can do it like this:
localStorage.removeItem("selectedProduct");

React manage array multidimensional by its index

I have a problem how to update(in this case Add or Remove Cargo) my multidimensional array based on the selected index. The parent array has been successful, but I am confused for the child how to process the data when clicking the Add Cargo button to add cargo and the Remove Cargo button to delete all cargo based on the selected index.
Please help. This is my codesandbox code
Sorry for the view, maybe is not good enough
You will need to provide index to the functions to add and/or delete cargos. In the function update the nested fields by mapping over the inputFields. While calling the handleAddCargo, pass the index and while calling handleRemoveCargo, pass the index as well as finalIndex which is the cargo array index.
const handleAddCargo = (parentFiledIndex) => {
const updatedInputFields = inputFields.map((item, i) => {
if(parentFiledIndex === i){
return {...item, cargo: item.cargo.concat({
cargoId: '',
cargoDescription: "",
cargoHsCode: ""
})}
}else{
return item
}
});
setInputFields(updatedInputFields);
console.log("add by its index cargo here");
};
const handleRemoveCargo = (parentFiledIndex, cargoIndex) => {
const updatedInputFields = inputFields.map((item, i) => {
if(parentFiledIndex === i){
return {...item, cargo: item.cargo.filter((cargo, c) => c !== cargoIndex)}
}else{
return item
}
});
setInputFields(updatedInputFields);
console.log("remove by its index cargo here");
};
updated working solution is here
https://codesandbox.io/s/reverent-bose-c2nkk
quick note -
try not to use array indexes while rendering lists. For eg, use some library to generate unique id

Categories

Resources