I'm setting up a basic WebApp here using ReactJS. Right now I can add data to my database using POST request no problem, the thing, my backend response sends me a JSON with all the data that I passed and the _id in the database. I need to get this _id and save it in my state so I can pass it along to the next URL in my WebApp. That's the code for my POST request :
SubmitClick(){
if (this.state.password !== this.state.reTypepassword){
alert('Passwords do not match. Please check your data !');
} else {
//console.log(this.state); //debug only
fetch('http://localhost:4000/users/', {
method: 'POST',
headers: {
'Accept': 'application/json',
//'Authorization': 'Basic YWRtaW46c3VwZXJzZWNyZXQ=',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.email,
first_name: this.state.first_name,
last_name: this.state.last_name,
personal_phone: this.state.personal_phone,
password: this.state.password
})
})
.then(response => response.json())
.then(parsedJSON => console.log(parsedJSON._id))
.catch(error => alert('Check your data', error))
.then(this.props.history.push('/get')) // change page layout and URL
}
console.log(this.state.id); //debug to see if the _id is saved in my state
}
Here is my constructor:
constructor(props){
super(props);
this.state={
email:'',
first_name:'',
last_name:'',
personal_phone:'',
password:'',
reTypepassword:'',
id:''
}
}
I tried calling a function after parsedJSON that used this.setState(), using function(parsedJSON){this.state.id : parsedJSON._id}. I tried with a new function like this:
changeID(parsedJSON){
this.setState({id : parsedJSON._id})
}
and changing the .then(parsedJSON => console.log(parsedJSON._id)) to .then(parsedJSON => this.cahngeID(parsedJSON)). But none of then worked...
I left the code with .then(parsedJSON => console.log(parsedJSON._id)) so can make sure that I can see this value, and in my console it`s printed perfectly.
Here is a example of the response send by my backend: {"email":"testing#gmail.com","first_name":"TESTER","last_name":"Testing","personal_phone":"(55) 2020-5252","password":"12345","_id":"5a27f511cd7d7a0db8ab65b9"}
How can I get the "_id" from my response?
You should not touch the this.state property directly. React will throw an error if you do this because React needs to know when this.state has been updated so that it can keep track of the changes. It cannot do this if you manipulate the property directly. That's why we have React.Component#setState. The "shallow" version is the most commonly used, where you pass an object that will be merged into your state. For example, the following:
.then(parsedJSON => this.setState({ id: parsedJSON._id }))
is equivalent to:
Object.assign(this.state, { id: parsedJSON._id });
except that React gets to keep track of when the state is updated.
Note that setState is also asynchronous and takes a callback as the second parameter. You can read more about that here.
As per the comment below, this other Stack Overflow question was helpful to the OP (Why calling react setState method doesn't mutate the state immediately?)
At the end of your constructor add this line of code:
this.SubmitClick = this.SubmitClick.bind(this);
because JavaScript does not bind the instance value of 'this' to our methods.
Related
I'm getting APN Invalid parameter: JSON must contain an entry for 'default' or 'APNS_SANDBOX'. the log is here
And the code block is here:
how to fix this? this is built in scala lift framework.
This is the example in javascript. In the same way, we have to use. Need to use cases for
1.APNS_SANDBOX
2.APNS
3.default
// Setup SNS Client
const snsClient = new SNS();
// whatever your full endpoint arn is. (from createPlatformEndpoint)
const endpointArn = 'arn:aws:sns:...';
// any extra data you want passed along with the message
const payload = {
someCustomKey: 'someCustomValue'
};
// send it
snsClient.publish({
TargetArn: endpointArn,
MessageStructure: 'json', // so we can put in a custom payload and message
Message: JSON.stringify({
default: `DEFAULT MESSAGE ${message}`,
APNS_SANDBOX: JSON.stringify({
aps: {
alert: `IOS Sandbox SPECIFIC MESSAGE ${message}`,
},
payload,
}),
APNS: JSON.stringify({
aps: {
alert: `IOS Prod SPECIFIC MESSAGE ${message}`,
},
payload,
}),
}),
}).promise().then(() => {
console.log('Notification sent!');
}).catch((err) => {
console.log('Failed to send with:', err);
});
Used this link for reference
I'm doing the wikipedia viewer from FCC projects with React, Im trying to make the request by just passing it the searchQuery (from my state) with template string. Like this:
gettingArticle() {
const { searchQuery, articlesList } = this.state;
const API = `https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json'};
const myRequest = new Request(API, body);
fetch(myRequest)
.then(response => response.json())
.then(data => this.setState({
articlesList: data, articles: true }));
console.log( 'data fetched' + displayedArticles);
}
I don't know for sure if is like this that I have to made the request it's just what I saw on the docs. I want to made the request and after receive the data I want to iterate over the array of objects and put every little thing that I need in their corresponding tag inside a div. Here is my entire code: https://codepen.io/manAbl/pen/VxQQyJ?editors=0110
The issue is because you missed a key details in the API documentation
https://www.mediawiki.org/wiki/API:Cross-site_requests
Unauthenticated CORS requests may be made from any origin by setting the "origin" request parameter to "*". In this case MediaWiki will include the Access-Control-Allow-Credentials: false header in the response and will process the request as if logged out (in case credentials are somehow sent anyway).
So I update your url like below
const API = `https://en.wikipedia.org/w/api.php?action=query&origin=*&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
And also your console.log was at the wrong place, so I changed it to below
fetch(myRequest)
.then(response => response.json())
.then(data => {
console.log( 'data fetched', data);
this.setState({
articlesList: data, articles: true })
});
Below is a updates pen
https://codepen.io/anon/pen/BxMyxX?editors=0110
And now you can see the API call works
Of course I didn't check why you have white strip after the call is successful, but that may be something wrong you do in your React code
The problem is not really in your code but in CORS, basically you are not allowed to make the call because of same origin policy.
Change these 2 constants
const API = `https://crossorigin.me/https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=${searchQuery}&prop=info&inprop=url&utf8=&format=json`;
const body = { method: 'GET', dataType: 'json', mode: 'cors', cache: 'default'};
I added crossorigin url before your API because it 'overrides' CORS and enables you to make calls outside the same origin policy. You should also modify your submit function:
handleSubmit(ev) {
ev.preventDefault(); //This disables default form function (reload/redirect of website and loss of state)
this.gettingArticle();
}
rq.js
}).then((responseData) =>{
this.setState({
user:responseData.name,
user1:responseData.blood,
user2:responseData.location,
loaded: true,
})
This is my code in react native.It works perfect if my JSON response is not an array.What change do i need to make in this code to work perfectly if json is an array?Showing this error Unexpected token < in JSON at position 1
data.json
[{"name":"hema","bld":"O -ve","lc":"london"}]
this is my json array input.Anybody please help..
try sending the data as a object not as array
{"name":"hema","bld":"O -ve","lc":"london"}
and actually you are calling props blood and location, but your JSON content bld and lc for that props
If You want it work with an array just do
}).then((responseData) =>{
this.setState({
user:responseData[0].name,
user1:responseData[0].blood,
user2:responseData[0].location,
loaded: true,
})
in this way you are calling the first object of the array's index and then the prop of this first object in the array
I know it's too late, but I hope it's helpful for others. How to fetch the response of JSON array in react native?
export default class ExpenseNew extends Component {
constructor(){
super();
this.state={
accountnameMain:[],
}
}
componentDidMount(){
var account_nam=[]
fetch('your Url', {
method: 'GET',
headers: { 'Authorization': 'Bearer ' + your token }
})
.then((response) => response.json())
.then((customerselect) => {
// alert(JSON.stringify(customerselect))
global.customerdata = JSON.stringify(customerselect)
var customername = JSON.parse(customerdata);
//alert(JSON.stringify(customername));
for (i = 0; i < customername.cus_data.length; i++) {
var dataa = customername.cus_data[i]["account_name"];
account_nam.push(dataa)
}
this.setState({accountnameMain:account_nam});
})
.done();
}
account_name is my field/column name, in your case, your column name is bld so you can fetch all data and push in var type of array, then set data in state type of array, and map anywhere you want.
I'm using the fetch-api for the first time and having trouble passing a non-stringified JSON objects to the server.
Basically I want to achieve the same behavior as this:
$.post(url, {"test": "test"}, function(response) {
console.log(response);
});
The fetch method is communicating with an web API which is unaccessable for me and expects a plain JSON object.
Normally I would just use FormData to pass data to the server, however the JSON will be transformed to a string [Object object]:
fetch(url, {
method: 'POST',
body: {"test": "test"}
})
.then(data => data.json())
.then(json => console.log(json))
.catch(e => console.error(e));
The body request seems to be empty when using $_POST (which is what the API is using), though gives the right value when using file_get_contents('php://input).
I though this had something to do with the wrong header given to the request. So I tried to add the header Ajax post uses: content-type:multipart/form-data;. However, this also did not get any value.
I was wondering if this was explicity intentional to not use plain JSON object to give as data, or that I'm simply missing something?
This does work, but is not allowed as it is a stringify version of the JSON object:
var formData = new FormData();
formData.append('data', JSON.stringify(data));
fetch(url, {
method: 'POST',
body: formData
})
.then(data => data.json())
.then(json => console.log(json))
.catch(e => console.error(e));
Let's say your data is inside a variable var data = { a: "some data", b: 123 }. If you want your code in PHP to access these fields this way:
$_POST["a"] == "some data";
$_POST["b"] == 123;
Then you need to send the data in the formData format this way:
var fdata = new FormData();
fdata.append('a', 'some data');
fdata.append('b', '123');
Now you can send that data and PHP will have access to separated fields a and b but notice b will be a string, not a number.
What if you want to send an array. Let's say { c: ['hello', 'world', '!'] }? You must follow PHP name conventions and add the same name multiple times:
var fdata = new FormData();
fdata.append('c[]', 'hello');
fdata.append('c[]', 'world');
fdata.append('c[]', '!');
After setting the form data instance, you can use it as the body of the request.
So firstly, I need to post to the POST-protocol, which is used by $_POST. I do this by adding a header of application/x-www-form-urlencoded (which is the protocol used by $_POST, as described in the docs) to the fetch post request:
fetch(url, {
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), // Default header which $_POST listens to
...
Now the way $.post actually sends data is by creating a serialized string (eg: a%5Bone%5D=1) of the given object. To transform an object to a serialized string, you can use $.param:
fetch(url, {
headers: new Headers({'Content-Type': 'application/x-www-form-urlencoded'}), // Default header which $_POST listens to
method: 'POST',
body: $.param(data)
})
This will make you able to retreive data from $_POST like you would do with a simple $.post.
I am trying to follow these directions: https://angular.io/docs/ts/latest/guide/server-communication.html and get the list of objects from the server in form of an object (not json).
I have a model class (simplified for now):
export class Goal {
id: number;
title: string;
}
And I am trying to get list of these from the server through a service class as follows:
export class GoalsService {
constructor(public authHttp:AuthHttp) {
}
getGoals() {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
<Goal[]> res.json()
}
)
.do(data => console.log(data))
.catch(this.handleError);
}
...
And the client using the service class is:
loadGoals() {
this.goalsService.getGoals().subscribe(
goals => this.goals = goals
);
}
The request goes through properly and I am getting back:
[{"id":1,"title":"target"}]
However, in the client, inside subscribe, goals variable is always 'undefined'.
I tried debugging it, this is what I get:
Which says to me that json received and parsed properly, but casting it into a target object is not working (unless I am not fully getting the mechanism).
What am I doing wrong?
Thanks,
Note: the authHttp service that I use is this guy: https://auth0.com/blog/2015/11/10/introducing-angular2-jwt-a-library-for-angular2-authentication/. And it works in all other places as expected. So I doubt that it is a peoblem.
As you are using map arrow function, you should return mapped result.
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => {
return <Goal[]> res.json(); //return mapped object from here
}
)
OR
return this.authHttp.get('<%= BACKEND_BASE_URL %>' + '/rrm/api/v1/goals', options)
.map(res => <Goal[]> res.json()) //or simply do map object directly