How to update a record in react native - reactjs

I am using firebase to store my data. When I am adding or getting data, there is no problem. But I can't update an existing report. For example, I have notes. And user can open a note, edit and save. On save, it should save the changes on existing record. But I can't do that.
Here is how I tried.
fetch('https://shared-places-***.firebaseio.com/notes.json/' + this.state.updatedNote,{
method:'POST',
body: JSON.stringify({
Header: this.state.newNoteHeader,
Explanation: this.state.newNoteSub,
Date: new Date(),
})
})
.then(res => console.log(res))
.catch(err => console.log(err))
I have added my id to request link hoping I directly effect it but it didn't work. Also tried changing method to Update but also didn't work of course. I have searched but couldn't find an answer.
Thank you in advance.

I have found the answer that I was making small mistakes. First of all, method should be PUT not POST. Also address should be https://shared-places-***.firebaseio.com/notes/' + this.state.updatedNote + '.json'

Related

Adding a collection to a document in Firestore

The way I have my file structure set up right now is that I have a main folder calles users. In that folder we have a document with a randomly generated name that contain some information along with another folder for files. I would like to duplicate this only using code. I could either run a function to build a template from scratch, or build a function to duplicate a file along with its subfolders.
Fyi, the file tree goes as such - [users] -> [user_document/user_information] -> [images]
I have yet to find any resources about this online, or maybe I'm not looking in the right areas, either ways, thanks for your help.
To add a new document to a collection, use the add method on a CollectionReference:
import firestore from '#react-native-firebase/firestore';
firestore()
.collection('Users')
.add({
image: "https://images.pexels.com/photos/10640445/pexels-photo-10640445.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
})
.then(() => {
console.log('User added!');
});
The add method adds the new document to your collection with a random unique ID. If you'd like to specify your own ID, call the set method on a DocumentReference instead:
import firestore from '#react-native-firebase/firestore';
firestore()
.collection('Users')
.doc('ABC')
.set({
image: "https://images.pexels.com/photos/10640445/pexels-photo-10640445.jpeg?auto=compress&cs=tinysrgb&w=1260&h=750&dpr=1",
})
.then(() => {
console.log('User added!');
});
For more details refer to the docs
Hope this helps. Happy Coding :)

Cypress testing and waiting for axios requests

Can anyone explain how or why my test isn't waiting for my data from an axios request before moving on? I'm completely new to this but have most simple stuff worked out but can't seem to navigate the docs to find where i'm going wrong.
Here's the relevant info..
cy.get('.day').eq(4).click() //Change the day
cy.route('/api/practice/available-slots').as('apiCheck') //Get available slots for that day
cy.wait('#apiCheck') //Wait for the days available slots to be returned
So you can see below I click the fourth day and my post URL is showing and getting data like it normally does but then my wait function throws that error. I like to think i'm close but as I said i'm new and not entirely sure what's going wrong. Thanks
For what it's worth here's the axios request:
axios
.post(this.props.reqProto + this.props.reqHost + '/api/practice/available-slots', {
startDate: this.state.appointmentSlotsDate,
})
.then((res) => {
....
}
})
Thanks Hiram,
That was one issue. Also the order of my code was incorrect. I need to allow cypress to anticipate the POST request instead of it trying to double back to it. This seems to work
cy.route({
method: 'POST',
url: '/api/practice/available-slots',
}).as('apiCheck')
cy.get('.day').eq(4).click()
cy.wait('#apiCheck')

patch request using axios fail in directusCMS

i am trying to send a patch request to update or maybe change the image in directus CMS.. (changing it require only id of the item and the file which is already solved.. in this link
Make Multiple Post Requests In Axios then get all the response to make another request)
below is the simplified code of it because the thing i am trying to achieve is making an item that have name, email, date, etc. then sending file or an image to the files ..
then i need to patch the item that i just made which is where i am not able to do yet..
for information only.. i am using gatsbyjs..
i have already tried it in postman and it works.. maybe there is something wrong with my code. thanks..
axios.patch( `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar/49?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`, {
data: JSON.stringify( {
kartu_keluarga: 1,
}),
})
i deleted JSON.stringify and it works
axios( `${process.env.GATSBY_DIRECTUS_API_URL}/gemaclc/items/pendaftar/50?access_token=${process.env.GATSBY_DIRECTUS_TOKEN}`,
{
method:"patch",
data :{
kartu_keluarga: 1,
nama: "zidsadanaaa"
},
}
)

CSRF Validation Failed in Drupal 7

I've been searching and searching, including the many topics here, for a solution to my problem. I've had no luck thus far.
A bit of a backstory: I'm writing an AngularJS app with Drupal 7 as a backend. I'm able to login without problem, save Session Name and Session ID, and put them together for a Cookie header (I had to use this "hack"). Further, if I made a login call in the Postman app, then tried to update the node, it'd work. It makes me think that there's a problem with session authentication, but I still can't figure it out.
That being said, I'm at a roadblock. Whenever I try to PUT to update a node, I get the following error:
401 (Unauthorized : CSRF validation failed)
Now, my ajax call looks like this:
$http({
method: 'PUT',
url: CONSTANTS.SITE_URL+"/update/node/"+target_nid,
headers:{
'Content-Type': CONSTANTS.CONTENT_TYPE,
'Authentication': CONSTANTS.SESS_NAME +"="+CONSTANTS.SESS_ID,
'X-CSRF-Token' : CONSTANTS.TOKEN
},
data: {
(JSON stuff)
}
})
The CONTENT_TYPE is "application/json", the "Authentication" is the band-aid for the Cookie header problem, and the "X-CSRF-Token" is what is (presumably) giving me the problem. SESS_NAME, SESS_ID, and TOKEN are all gathered from the response at Login. I can pull lists made by users on the website, I can pull the list of all of the nodes of a certain type on the website as well. I only run into a problem when I attempt to PUT to update the node.
If I missed any information, let me know and I'll add it!
EDIT: I'm using AngularJS version 1.5.3.
After trying everything else, I followed one of the comments in the thread I linked at the beginning of my original post. They had to comment out a line in Services.module :
if ($non_safe_method_called && !drupal_valid_token($csrf_token, 'services')) {
//return t('CSRF validation failed');
}
It's around line 590, plus or minus a few depending on how much you've messed with the file. I don't like doing it this way, but I can't for the life of me figure out why the token's not working right. It's a temporary fix, for sure, but if someone runs across this with the same problem in the future it'll hopefully help you out!
Instead of removing the line you could also add a true to drupal_valid_token
if ($non_safe_method_called && !drupal_valid_token($csrf_token, 'services',true)) {
return t('CSRF validation failed');
}

Setting a variable out of a confusing method in Angular JS

So I have a variable called stuff, which is declared as stuff:any and I would like to populate it with the data that I get from:
this.http.post("WORKING_IP_ADDRESS", JSON.stringify(
{"thing1": this.thing1,
"thing2": this.thing2,
}), {headers: headers}).map(
res => res.json()).subscribe(
data => {
(JSON.stringify(data));
})
When I run an alert() method on the last JSON.stringify(data));, I get the data that I want, but when I try to set it equal to the stuff variable by doing this.stuff = JSON.stringify(data));, it doesn't work. I'm new to Angular, so I know I'm probably doing something wrong. Anyone know what I need to do to get the final JSON.stringify(data) into my stuff variable?
The reason is that http.post is a observable. That means that its gonna resolve later. It's gonna resolve later because its gonna take some time to connect to that working ip address, get the data and do something with it.
Imagine a scenario like this
let stuff = 'no';
// Equal to http.post
const resolvesLater = setTimeout(function() {
stuff = 'yes';
console.log(stuff);
},2000);
console.log(stuff);
https://jsfiddle.net/7c6kfurp/ Open up the console and press play. See what happens.
You would think that the console would look like
yes
yes
But it actually is gonna be
no
yes
Because what happens in the setTimeout happens later. So the order of the lines don't tell you in what order the code executes.
Its gonna set stuff = 'no' at the beginning.
Then its gonna go into the setTimeout/http.post function
That's gonna take some time.
Meanwhile the browser continues
It logs out stuff (still no)
Then the setTimeout/http.post resolves
Its gonna set stuff = yes
Then log out stuff (which is now yes)
In angular 2 you subscribe to observables (like you do) but it would probably be better to decouple the fetch and subscribe. So create a service with a function:
fetchStuff(): Observable<Stuff[]> {
return his.http.post("WORKING_IP_ADDRESS", JSON.stringify({
"thing1": this.thing1,
"thing2": this.thing2,
}), {headers: headers}).map(res => res.json());
}
And then you subscribe to it and assign the stuff variable for the views
getStuff() {
this.MyService.fetchStuff()
.subscribe(stuff => this.stuff= stuff);
}
And finally in your view
<ul class="items">
<li *ngFor="let item of stuff>
<span>{{item.property}}</span>
</li>
</ul>
Observables means that when the object changes all other objects that are dependant on it are notified.
So you make a request to your working-ip, first nothing happens, like I explained above. We're waiting for the server to respond, so something with the data you sent and then send you something back.
In order to know when something happened, you subscribe to it. Just like you would subscribe a newspaper to get the latest news. When something happens you get notified. You want to know when you get response from the-working-ip.
The reason I broke it up was to seperate the fetching and the subscription, just to seperate the concerns. You don't have to and I've probably confused things more for you. Sorry about.
Simply try this:
this.http.post("WORKING_IP_ADDRESS", {
"thing1": this.thing1,
"thing2": this.thing2
}, {headers: headers})
.map(res => res.json())
.subscribe(data => this.stuff = data);
Here's a link on how to create services
https://angular.io/docs/ts/latest/guide/server-communication.html

Resources