React Native - Parsing error from JSON Response - json

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');
});

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);
});
});

TypeError: JSON.stringify(...).then is not a function - React JS

I am trying to connect my react app with the backend for log in page. I am using a promise to return a success message.
login.js
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
})
}
Backend code -
exports.findById = (req) => {
return new Promise((resolve) => {
var sql = "Select * from users where userid = '" + req.body.userId + "' ;";
connection.query(sql,req, function (error, results, fields) {
var data = JSON.parse(JSON.stringify(results));
var valid = false;
if( data.length !=0 && req.body.userId === data[0].userid && req.body.password === data[0].password)
valid = true;
if(valid) {
resolve({message : "success"});
}else{
reject({ message :"fail"});
}
});
})
};
After clicking on sign in button, I am getting an error "TypeError: JSON.stringify(...).then is not a function"
I tried some solutions from similar questions, it did not work in my case.
The then should be outside of fetch
fetch('http://localhost:5000/', {
method : 'post',
headers :{ 'Content-Type' : 'application/json'},
body : JSON.stringify({
userId : this.state.userId,
password : this.state.password
})
}).then(response => response.json())
.then(data => {
if(data === 'success'){
this.props.onRouteChange('home');
}
})
You have a typo, .then should be on fetch not on JSON.stringify.
onSubmitSignIn = () => {
fetch("http://localhost:5000/", {
method: "post",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
})
//-^
.then(response => response.json())
.then(data => {
if (data === "success") {
this.props.onRouteChange("home");
}
});
};
you have missed a bracket. there should be a closing bracket after JSON.stringify().
onSubmitSignIn = () => {
fetch('http://localhost:5000/', {
method: 'post',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
userId: this.state.userId,
password: this.state.password
})
}).then(response => response.json())
.then((data) => {
if (data === 'success') {
this.props.onRouteChange('home');
}
});
};
I had this problem too. Check and confirm that you're not importing or requiring {JSON} in your application. It's most likely referring to that imported JSON rather than the global

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

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')})
}

Unhandled promise rejection Error: Cannot read property 'json' of undefined

answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
return fetch(BASE_URL + url, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body: JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
}
}
}
})
});
})
I used map function so that on every map it should go to JSON.stringify and assign the values. But I got error "Unhandled promise rejection TypeError: Cannot read property 'json' of undefined". please suggest me any solution.
Thanks in advance.
Here you are creating an array of fetch promises, we need more info about how you handle these promises after that, i suppose you're trying somewhere to get a response from these promises using .then(res => res.json()) but your server response is not in json format.
To handle a fetch promise rejection you need to do this:
fetch(smth)
.catch(error => //handle the error e.g. console.log(error))
To see if there's something wrong in your request json body you can log it server side or log it before sending, you can also log the server response, try this to identify what's wrong:
answers.map((answer, index) => {
answer_text = answer.answer_text;
id = answer.id;
const body = JSON.stringify({
question: {
answers_attributes: {
'0': {
answer_text: answer_text,
id: id
} }
}
})
console.log('Json body request :', body);
return fetch(BASE_URL + url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Authorization': 'Token token=' + token
},
body
}).then(res => {
console.log('server response :', res);
return res;
}).catch(err => console.log('Fetch error :', err));
})
I recommend using an app like Postman to test the responses from your api server (easier & faster to debug request/responses from an API)
Edit: I also think you want to do a POST request instead of PUT.