fetch data error with react native - javascript

I used two classes
I call the second class as below
let s = new SearchExtend();
output = s.fetchData(search)
alert(output)
The second function:
fetchData = (search) => {
fetch('http://example.com/search.php' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Getting the search.
search: search
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
But i get in "alert" undefined
When I use this.setState instead of return, I get the following error:
warning setstate(...) can only update a mounted or mounting component

You are getting undefined because you are using promises. Initially it returns undefined and once promise is resolved you get the actually data.
A better way to handle this would be to return the promise and resolve it externally as follows:-
const fetchApi = () => {
return fetch("https://swapi.co/api/people" , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => {
return response.json();
})
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(JSON.stringify(error));
});
}
fetchApi()
.then((data) => {
console.log("data", data);
})

Related

Response data returns undefined from asp.net web api to vue.js

currently I'm fetching data from my api to front-end. I checked and my request body is arriving to server side. But after doing things when it comes to returning the token it always returns undefined data to vue.js:
[HttpPost("login")]
public async Task<IActionResult> Login([FromBody]User user)
{
var result = await _accountRepository.LoginAsync(user.username, user.password);
if (string.IsNullOrEmpty(result))
{
return Unauthorized(result);
}
Debug.WriteLine(result.ToString()); // this works and I can see the token
return Ok(result);
}
When it comes here:
methods: {
login() {
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
}).then(response => {
console.log(response.data); // this is always undefined
})
.catch(e => {
console.log(e);
});
},
}
Please help I can't see any errors here. I'm confused.
You need to call either Response.text() or Response.json() depending on what data you expect. These methods return a Promise that resolves to the data.
E.g. for JSON:
fetch("http://localhost:60427/api/account/login", {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
username: this.username,
password: this.password,
})
})
.then(response => response.json())
.then(data => console.log(data))
.catch(e => console.error(e));

Getting data from metaweather API to react page

I tried to use this metaweather API but it's not working. this is a react project and I'm tyring on localhost. plz, can anyone show me what am I doing wrong here?
const fetchWeatherData = async() =>{
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
console.log('response',response);
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})}
these are logs i got
You just didn't close the function with curly brackets, I have tested it and it works fine , just call the function fetchWeatherData
const fetchWeatherData = async() => {
fetch('https://www.metaweather.com/api/location/search/?lattlong=36.96,-122.02', {
method:'GET',
mode:'no-cors',
headers: {
'Content-Type': 'application/json',
},
})
.then(response => {
return response.json();
})
.then(data => {
console.log('data',data);
})
.catch((err) => {
console.log(err)
})
}
fetchWeatherData()

get the return value of an arrow function using React

I have this arrow function:
saveNewPermissions = (newGroupPermissions, groupName) => {
fetch(this.baseUrl + "/addPermission/group/" + groupName, {
method: 'PUT',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify({
permissions: newGroupPermissions
})
}).then(response => response.json())
.then(json => {
console.log(JSON.stringify(json))
return json;
});
}
That function above is on the Service file, and on my component class i want to get the json that the function returns:
this.Service.save(newList, groupName)
I tried to do this but it didnt work:
this.uaaService.saveNewPermissions(newList, groupName).then(response=>{
console.log(response)
})
First of, you would want to return the Promise from the arrow function
saveNewPermissions = (newGroupPermissions, groupName) => {
return fetch(...) // returns a Promise object
}
then if you expect newList to be an array, you want to do:
this.uaaService.saveNewPermissions(newGroupPermissions, groupName).then((newListJSON) => {
this.Service.save(newListJSON, groupName);
})

ReactJS several fetch requests with promise

I need several fetch requests in my application to fetch data from different collections. Therefore, I wanted to use promises to make it work.
I have never used promises and despite my research on stackoverflow and other websites, I was not able to make it work.
Essentially, I need two fetch requests and I want to save the result of these requests to 2 different states.
This is what I have as of right now:
getFormData () {
fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getData () {
return Promise.all([this.getFormData(), this.getIcons()])
}
componentDidMount () {
this.getData()
.then(([formdata, icons]) => {
console.log(form + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this did not work.
I also tried putting the promise in my componentDidMount() lifecycle method, like so:
componentDidMount () {
return Promise.all([this.getFormData(), this.getIcons()])
.then(([formdata, icons]) => {
console.log(formdata + " " + icons);
})
.catch(err => console.log('There was an error:' + err))
}
But this didn't work eiter.
I would like to save the data from /formdata to a state with the same name and the same goes for icons, but in the console it simply returns undefined undefined, instead of the formdata and the icons.
Where am I making a mistake in my code? How would I fix it?
You need to return Promise object from your methods. As of now you are not returning anything, so it's implicit undefined.
Try this:
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json())
}
Just adding to #dfsq's answer, after returning the promises you can update the state within each function:
constructor(props) {
super(props);
this.state = {
formData = {},
icons: {}
}
}
getFormData () {
return fetch('/formdata', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ formData: res.json })
))
}
getIcons () {
return fetch('/icons', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}})
.then(res => res.json(
this.setState({ icons: res.json })
))
}

Sending results from fetch to another part of program

I am creating an app in React Native and have bumped in to some major issues with fetching data from my server and using it in my program.
My architechture differs a bit from the example provided by React Native in their documentation, but I have tried a bunch of different ways. The token is correct and I am obviously calling the method in a sense correctly, but it does not return the data to the other side of my program.
In Methods.js
exports.loginUser = function(TOKEN) {
fetch(baseUrl + 'login' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessToken: TOKEN,
},)
})
.then((response) => response.text())
.then((responseText) => {
console.log(typeof responseText);
return responseText
})
.catch((error) => {
console.warn(error);
});
};
Where it logs the type of the data as a string, and it prints out correctly when I call it as is. However, my app can't retrieve the data in any kind of manner, it just returns as undefined.
In Home.js
var Method = require('../Services/Methods');
.
.
.
var ComponentTwo = React.createClass({
getInitialState: function() {
return {
text: 'Loading...',
}
},
componentDidMount: function() {
{
this.setState({
text: Method.loginUser(AccessToken)
})
}
},
render: function() {
console.log(Method.loginUser(AccessToken));
console.log(this.state.text);
I am in trial and error mode right now, but both of the logs returns undefined, except for my log in Methods.js, so I think there is an issue with just hitting return responseText, but I don't know any other way since they are in two separate files. So I think the issue is within Method.JS since calling it fails in every way I've tried.
I think you have to return a promise from your loginUser function, something like:
exports.loginUser = function(TOKEN) {
return new Promise((resolve, reject) => {
fetch(baseUrl + 'login' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
accessToken: TOKEN,
},)
})
.then((response) => response.text())
.then((responseText) => {
console.log(typeof responseText);
resolve(responseText);
})
.catch((error) => {
reject(error);
});
});
};
And then call your function like this:
Method.loginUser(AccessToken)
.then((res) => console.log(res))
.catch((error) => console.log(error))
.done();
I have not verified that the above code is working, it's just to give you an idea.

Categories

Resources