how to fetch api(POST) with header in react native app - json

I am trying to put three params in my post request to particular api but i didn't get the response as i expected. API works fine in my Postman but i am not sure about my fetching method in my react native app i am new to this so i don't know how to put headers in my api request i followed some docs but didn't get much please have a look and answer my question.
constructor (props) {
super (props)
this.state = {
detail: ''
}
}
ComponentDidMount(){
var data = new FormData();
data.append('mobile_number','8615351655')
data.append('mobile_country_code','+21')
data.append('rec_name','Shantanu Talwaar')
}
fetchData = async() => {
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
//this what's exactly look in my postman
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;
},
body: this.data
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson.detail)
}).catch((error) => {
alert('error')})}
render() {
return (
<View style = {styles.container}>
<Button onPress = {this.fetchData} title = "fetch"/>
<Text style={styles.text}>Fetched data displays below</Text>
<Text style={styles.text}>{this.state.detail}</Text>
</View>
)
}
}
This is the result i am having right now in my alert box: "Authentication credentials were not provided."

There is a ' missing after your token.
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb;
And as it is a JSON Object you should remove the semi-colon
So, the final code will be
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
There is also another problem. The data declaration is not accessible from the fetch function. So you should do something like this.
fetchData = async() => {
var data = new FormData();
data.append('mobile_number','8615351655')
data.append('mobile_country_code','+21')
data.append('rec_name','Shantanu Talwaar')
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
//this what's exactly look in my postman
'Authorization': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
},
body: data
})
.then((response) => response.json())
.then((responseJson) => {
alert(responseJson.detail)
}).catch((error) => {
alert('error')
})
}

i think you can use "x-access-token" as header name for authentication token and place Content-Type too.
fetchData = () => {
fetch('http://link.com/link/',
{
method: 'POST',
headers:{
'Content-Type': "application/json",
'x-access-token': 'Token 97a74c03004e7d6b0658dfdfde34fd6aa4b14ddb'
},
body: this.data
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson.detail)
}).catch((error) => {
alert('error')})
}

Related

How to fetch data from Api which is coming from php file

I am trying to get data from an api but the thing is the api has php extesnion. I am quite new to this thing and I really dont understand why i am not getting the data by using result.data.
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch(url, requestOptions)
.then(response => response.text())
.then(
result => {
console.log('result', result.data)
}
)
.catch(error => console.log('error', error));
It does not matter from where you are fetching the data you are making a silly mistake, the data format is in json but you are forcibly converting it to raw text so you have to replace result.data with only result e.g.
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
.then(response => response.text())
.then(
result => {
console.log('result', result) //now works
}
)
.catch(error => console.log('error', error));
for request.data to work you have to replace response.text() with response.json()
var formdata = new FormData();
formdata.append("stock_symbol", "PPL");
var requestOptions = {
method: 'POST',
body: formdata,
redirect: 'follow'
};
fetch("https://dev-api.sarmaaya.pk/3.0/company_fundamentals.php", requestOptions)
.then(response => response.json())
.then(
result => {
console.log('result', result.data) //now it works
}
)
.catch(error => console.log('error', error));

Undefined data after responseJson is entered into state [] in ReactJS

I have a problem here, namely when I do the Post API and add console.log (responseJson) the data appears and its contents are (app_uid and app_number). But when I enter the API data into the dataApp [] state and I try console.log (this.state.dataApp), no data appears.
Here is a piece of script from its post API function:
onTask = (pro, tas) => {
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
this.setState({
dataApp: responseJson,
});
console.log(this.state.dataApp); //but here does not appear any data
});
Hopefully I can find a solution here, thank you very much.
this.setState is an asynchronous function.
Meaning - in your example, that you won't see its result on the next line where you console log it, because it is not yet done.
Try the following:
this.setState({
dataApp: responseJson,
}, () => console.log(this.state.dataApp)); // console.log inside a callback
To understand why it works inside a callback, and not in the next line, take a look at this MDN Article and this React Documentation
setState() is an async call in React. So you won't likely get the updated state value in the next line. You need to use the callback handler to get the updated value.
onTask = (pro, tas) => {
//Code you need to add
var that = this;
fetch('https://bpm.***********.or.id/api/1.0/**********/cases/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept-Encoding': 'gzip, deflate',
'Authorization': 'Bearer ' + this.state.token,
},
body: JSON.stringify({
'pro_uid': pro,
'tas_uid': tas,
}),
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson); //here the data appears
that.setState({
dataApp: responseJson,
}, () => {
console.log("dataApp: ", that.state.dataApp);
});
});

I need to fetch API to get a raw value from response same as the result in POSTMAN but fail?

I am new from here. Just stuck on some problem of fetching the data from frontend(react) to the raw value in JSON. For the login part, when I enter the email and password, supposedly the response are same as the result in POSTMAN, but i get the error. I am figure out this issue for almost oneweek. I would be appreciate for those who help me to solve on this issue. I will elaborate further on below about my situation:
Here is the response of API from postman (supposedly I should get this response):
The result I get in the browser:
Source Code:
constructor (props){
super(props);
this.state ={
loginEmail: '',
loginPassword: ''
}
this.login = this.login.bind(this);
this.onChange = this.onChange.bind(this);
}
login(){
PostData('api/users/login', this.state).then ((result) => {
let responseJSON = result;
console.log(responseJSON);
});
}
PostData:
export function PostData(type, userData = {}){
let BaseUrl = "https://ems-unimas-58134.herokuapp.com/"
return new Promise((resolve, reject) => {
fetch(BaseUrl+type,{
method: "POST",
body: JSON.stringify(userData),
Accept: 'application/json',
// headers:{
// 'Content-Type': 'application/json'
// }
}).then(res => res.json())
.then((responseJson) => {
resolve(responseJson);
})
.catch((error)=>{
console.error('Error:', error);
})
});
}
Commend down here if anyone of you need more code.
The problem is you need to allow CORS.
You can read more about CORS in here

React Native - Second API Call is not returning value

My problem is that my code is returning an undefined value because of my second API Call:
render(){
const result_postid = this.state.data_one.map(function(val) {
return val.postid;
}).join(',');
const result_spaceid = this.state.data_one.map(function(vall) {
return vall.spaceid;
}).join(',');
//These two will receive values.
const result_image = this.state.data_two.map(function(valll) {
return valll.image;
}).join(',');
//This last one somehow will not receive value
}
Here I am fetching two APIs in the same componentDidMount:
componentDidMount(){
//First API Call
fetch(`http://www.exmaple.com/React/data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
data_one: responseJson,
},function() {
});
}).catch((error) => {
console.error(error);
});
// Second API Call
fetch(`http://www.example.com/React/image_data.php`, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((responseJson) => {
this.setState({
data_two: responseJson,
},function() {
});
}).catch((error) => {
console.error(error);
});
}
To confirm that it wasn't just a data response issue, I deleted the first to const (result_postid) and (result_spaceid) and the error was gone (TypeError: undefined is not a function (evaluating 'this.state.data_two.map(function(valll){return valll.image}')). The data showed successfully, but I need all 3 const to return the value. Is there a way to return all values for all 3 const?
The API calls are asynchronous, when you use the values in the render function some of them do not exist until all the calls return. You should have an initial state in the constructor
constructor(props) {
super(props);
this.state = {
data_one: [],
data_two: []
}
}
That way the values are not undefined. When the API returns the value, then the setState will trigger the render again.
Also, why do you have an empty function in the setState in the callbacks?
It should be something like
this.setState({
data_two: responseJson,
});
A couple of recommendations:
Use camelCase for variable naming, _ is not an usual standard in JS
Move the API calls to a different file, that will help you keep the component more organized. Then from componentDidMount you just call the function to make the request.

React Native - Parsing error from JSON Response

Here is my code.
I am calling the following function to get state list.
callGetStatesApi()
{
callGetApi(GLOBAL.BASE_URL + GLOBAL.Get_States)
.then((response) => {
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
});
}
Here is common callGetApi function for getting response from GET Api.
export function callGetApi(urlStr, params) {
return fetch(urlStr, {
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify(params)
})
.then((response) => response.json())
.then((responseData) => {
result = responseData
})
.catch((error) => {
console.error(error);
Alert.alert('Alert Title failure' + JSON.stringify(error))
});
}
I am getting the following error.
Alert only show the string , but your case "stateArray" is complex object (array,structure..)
So use stateArray.toString() or JSON.stringify(stateArray),
Or
Try the below method and let me know,
fetch(GLOBAL.BASE_URL + GLOBAL.Get_States, {
method: 'get',
headers: { 'Accept': 'application/json','Content-Type': 'application/json',}
}).then((response) => response.json())
.then((responseData) => {
console.log(responseData) // this is the response from the server
// Continue your code here...
stateArray = result.data
Alert.alert('Alert!', stateArray)
}).catch((error) => {
console.log('Error');
});