Deleting data from a mockapi.io json, with javascript - javascript

I am using mockapi.io for my first big learning project(ecomerce) and i can do get, post but seems like not delete. It deletes the row in the admin page table but not the product from the online api. Seems impossible to find info about this issue online, or i just don't know how to ask the right question. Maybe it's not even posible to really delete from a mock api?!
I am geting in the console: http.js:21 DELETE https://6060b8b904b05d0017ba2dfb.mockapi.io/products?id=50 400 (Bad Request)
So it does compose the right link to that specific product, but just doesn't delete it.
function deleteProduct(e) {
if (e.target.classList.contains("delete")) {
const id = e.target.id;
e.target.parentElement.parentElement.remove(id);
const productToDelete = `https://6060b8b904b05d0017ba2dfb.mockapi.io/products?id=${id}`;
http
.delete(productToDelete)
.then((data) => getProductsAdmin())
.catch("Error on delete!");
}
}
Let me know if you need printscreens or more code. Thanks

I think your parameter's link was wrong, it should be :
https://6060b8b904b05d0017ba2dfb.mockapi.io/products/${id}

the answer above is correct, and finding info about mockapi.io on the internet was hard for me so, I just wanted to answer to the related problems with mockapi.io when deleting a specific object from DB.
When adding new objects to the resource mockapi.io assigns an id to them. And when you want to delete that new object you should make a request(/products/${id}) to that assigned id, but the problem is if you have your own id in the object and mockapi.io assigns another id to this object when adding it to the resource, your request will address different object.
I solved it this way:
First, you change the name of the id that mockapi.io assigns automatically
For example, I changed it to "index"
https://i.stack.imgur.com/N6zY2.png
const { data } = axios.get(`https://UNIQUE_PROJECT.mockapi.io/cart?id=${thisCard.id}`);
await axios.delete(`https://UNIQUE_PROJECT.mockapi.io/cart/${data[0].index}`);
It finds an object with my assigned id, then I make a delete request with index(the id that mockapi.io assigns automatically to new objects).
Important to remember, a delete request(/cart/${id}) works only with identifiers (id, index, etc.) that mockapi.io assigns itself.

Related

How can I access the child of a unique key in Firebase?

I am trying to access the child value of a unique key value (that had been "pushed") within Firebase. Currently, my database looks like this: I want to access the value of "emailOfUser"
I am very new to Firebase so I am not familiar with the functions. Currently, this is my method of obtaining other values for a different section of the database:
Thank you so much for any feedback!
I've tried different methods to accessing this data within the Firebase, but I cannot get it to work/the methods I were using were outdated. I also tried to "update" the Firebase instead of "pushing" the values to prevent a unique key from generating, but it simply overwrote my current data rather than appending something new.
If you want to load all the users who voted and print their emails, you can do that with:
get(child(dbref, 'usersWhoVoted')).then((snapshot) => {
snapshot.forEach((childSnapshot) => {
console.log(childSnapshot.key, childSnapshot.val().emailOfUser);
});
})
Note that your current structure allows a user to vote multiple times. If you want to only allow them to vote once, use some identifier of the user as the key in your database structure:
userVotes: {
"uniqueIdOfUser1": "valueTheyVotedOn",
"uniqueIdOfUser1": "valueTheyVotedOn",
...
}
Now each user can by definition only vote once, If they vote again (assuming your security rules allow that), their new vote will simply replace the existing vote.

How to get and set a ref for a newly cached related object in Apollo client InMemoryCache?

I have a set of related items like so:
book {
id
...
related_entity {
id
...
}
}
which apollo caches as two separate cache objects, where the related_entity field on book is a ref to an EntityNode object. This is fine, the related entity data is also used elsewhere outside of the context of a book so having it separate works, and everything seems well and good and updates as expected...except in the case where the related entity does not exist on the initial fetch (and thus the ref on the book object is null) and I create one later on.
I've tried adding an update function to the useMutation hook that creates the aforementioned related_entity per their documentation: https://www.apollographql.com/docs/react/caching/cache-interaction/#example-adding-an-item-to-a-list like this:
const [mutateEntity, _i] = useMutation(CREATE_OR_UPDATE_ENTITY,{
update(cache, {data}) {
cache.modify({
id: `BookNode:${bookId}`,
fields: {
relatedEntity(_i) {
const newEntityRef = cache.writeFragment({
fragment: gql`
fragment NewEntity on EntityNode {
id
...someOtherAttr
}`,
data: data.entityData
});
return newEntityRef;
}
}
})
}
});
but no matter what I seem to try, newEntityRef is always undefined, even though the new EntityNode is definitely in the cache and can be read just fine using the exact same fragment. I could give up and just force a refetch of the Book object, but the data is already right there.
Am I doing something wrong/is there a better way?
Barring that is there another way to get a ref for a cached object given you have its identifier?
It looks like this is actually an issue with apollo-cache-persist - I removed it and the code above functions as expected per the docs. It also looks like I could instead update to the new version under a different package name apollo3-cache-persist, but I ended up not needing cache persistence anyway.

Firestore data modeling and angularFire

I have data model like this
Players-->root collection
Sports--->root collection
Players_Sports---root collection
I want get all the sports(Multiple sport) details or document player belongs.
For this I am using angularFireStore5
First, I am getting
Player details like this
this.db.collection('players').doc(id).get().toPromise()
Second, I am getting Player(user) linked PlayerSport
db.collection<any>('PlayerSports',ref => ref.where('playerId', '==', id) ).get().toPromise()
Third, I am trying to get Sports details based on ID'S,
db.collection<any>('sportsType', ref => ref.where('sportsType' 'in' [sportsIDs])).get().toPromise()
where SportIDs is arrary of ID that are linked in player_sports
First and Second steps works fine, but third steps is not giving any data or response
Could you please let me know where is the problem,
is it in Data model or code? my guess is that data model is not correct. Please guide me on this.
I would suggest getting the data from firebase and storing it inside a list so the app can access it later.
void getDataF(){
databaseReference
.collection("TableName")
.getDocuments()
.then((QuerySnapshot snapshot) {
snapshot.documents.forEach((f) {
iDFacList.add(f.documentID);
dbFacList.add(f.data["FieldName"]);
});
});
}
There is no sportsType field in the sportsType document as far as I can see.
If you're trying to find documents based on their SportsId field, you'll want ref.where('SportsId'....
Update
It seems that you're trying to find a document by its ID, which you can do with:
ref.doc(sportsIDs)
If you want to get multiple documents, or get a single document as a collection, you can use:
ref.where(firebase.firestore.FieldPath.documentId() 'in' [sportsIDs])

What does a child function do in Firebase?

I'm reading documentation for Firebase and I came to this part:
function writeNewPost(uid, username, picture, title, body) {
// A post entry.
var postData = {
author: username,
uid: uid,
body: body,
title: title,
starCount: 0,
authorPic: picture
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().**child('posts')**.push().key;
How am I supposed to understand this? Currently I'm thinking this is saying "from the root of the database, create a node and store its access key in a variable". What is the use of having a child function with 'posts'? I can run similar code like the following and get the same result.
var newPostKey = firebase.database().ref().push().key;
Your second bit of code does not really give the same result, when taken in the context of the rest of the code sample from the docs (that you didn't show here).
Actually, the code you've shown does not actually create any data in the database at all, because if nothing is passed to push(), then it just returns a reference to the location (with a unique key) that you can later write to. The part of the sample that you omitted actually performs the update.
The API docs for child() says:
Gets a Reference for the location at the specified relative path.
The method is helping you build a path to a reference. Without the call to child() in your second example, the reference will be at the root of the database, rather than under "/posts". While you will get a unique key in both situations, its location in the database will be different (after you actually write data there).

Ember deleting objects using em methods

Hai once again ive deleting action to take care of.
Ive array and parameter with given item to be removed
[
Class
,
Class
,
Class
,
Object>
__ember1393425759417_meta: Meta
formId: 4
proto: Object
Where classes are existing records in the database, i can delete them and it works (else block). PS! Parameter is the exact same object / class that needs to be deleted
deleteFieldset: function(formID){
if(this.get('controller').get('isEditController')){
//Checks if edit controller
var allPersonArray = this.get('controller').content._data.persons;
if(allPersonArray[formID.formId -1] !== undefined){
//TODO: Delete generated objects
}else{
formID.destroyRecord(); // Deleting records works.
}
}else{}
I tried removeAt, removeObject, but no luck.
Given output with removeAt on the newly generated object in the array.
TypeError: Object function Object() { [native code] } has no method
'inverseFor'
On the other hand i cant splice em either, cus that does not affect hbs...
It looks like you're having trouble creating records, so I'll try to explain. First, in the latest versions of Ember-Data, the store is supposed to create new records for you. Example:
var record = this.get('store').createRecord({
prop1: 'value1',
prop2: 'value2'
});
record.set('belongsToRelationship', otherRecord);
record.set('hasManyRelationship', new Em.Set());
records.save();
This will create a proper record for you, and when you call .save() on that record, the adapter will persist it to the server for you.
As far as primary keys go, you can't create those on the client side. Whatever you think might be working right now by just incrementing the last primary key, will not work when you have more than one client. (Hell, it probably won't even work now.) Your server is supposed to create the primary keys. You create a record, like I did above. When you save it to the server, your server should respond with a payload that includes the saved record, primary keys included. Ember-Data will then load that payload into the record you just created, populating the primary key fields.

Categories