I'm putting together a React app that consumes data from a Node/Express REST API which is currently on my local machine. I've got a simple res.json returning a Sequelize object, and I'm accessing it through a service I made. Obviously, I'm going to be putting the object in state eventually, but I'm currently having difficulty accessing the values.
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
.then(response => console.log(response.json()));
I'm getting the results in the console, but they're stuck in the [[PromiseValue]].
I must be missing some kind of async step, but I'm not sure what.
The json method returns a promise, which you also need to await. So do:
fetch('http://localhost:3000/users/sign_in', options)
.then(response => response.json())
.then(obj => console.log(obj));
You're having this error because response.json() return a promise.
you need to do
fetch('http://localhost:3000/users/sign_in', options)
.then(response => response.json())
.then(res => console.log(res));
You need to return the promise from the fetch call or else you need to act on it in the then for the json promise.
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
return fetch('http://localhost:3000/users/sign_in', options)
.then(response => {
console.log(response.json())
return response.json()
}
);
or...
const options = {
method: "POST",
headers: {
"Content-Type": "application/x-www-form-urlencoded"
},
body: JSON.stringify({email: "matthewharp#gmail.com", password: "M1nerals"})
};
fetch('http://localhost:3000/users/sign_in', options)
.then(response => {
console.log(response.json())
response.json().then( result => {
// whatever you're doing with the data here.
}
);
Take a look at the fetch api:
https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch
You need a separate then chained to take the json data once ready, and it will give you the values.
('http://localhost:3000/users/sign_in', options)
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
Related
I have never used fetch before, and have followed the documentation, however, no results are being returned from my backend. When I submit the form, the url changes, and all appears fine in my console, but no response from my express backend.
The following code is what I have after my form in a script tag. Can someone please advise?
async function getSample(url = `http://localhost:3000/lookup/${url}`, data = {}) {
const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
});
return response.json();
}
document.getElementById('search').addEventListener('submit', function(e) {
event.respondWith(
new Response(myBody, {
headers: {'Content-Type': 'application/json'}
})
);
});
You could try creating a promise and then handling the value returned by the fetch with resolve and reject
async function getSample(url = `http://localhost:3000/lookup/${url}`, data = {}){
return new Promise(function (resolve, reject) {
fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
}).then(async response => {
if (response.ok) {
response.json().then(json => resolve(json));
} else {
response.json().then(json => reject(json));
};
}).catch(async error => {
reject(error);
});
});
};
You would then call it like
getSample(...)
.then(results => {
//Code when fetch is successful
}.catch(error => {
//Code when fetch fails
};
I think the problem with it returning nothing is that getSample is an async function, but I imagine you're calling it within a program that isn't async, and so whatever code comes after getSample is using trying to use the value returned from getSample, but nothing's been returned yet, so it's using an empty value. Either that or the return of getSample is happening before the fetch completes. I'm not sure of the exact order that things happen, but a promise should fix your problem
I've seen several posts about this, so I apologize if it's a direct duplicate. The examples I've seen have the RN components built with classes. I'm using functions, and I'm new, so it's all very confusing.
const getFlights = async () => {
const token = await getAsyncData("token");
instance({
method: "get",
url: "/api/flights/",
headers: {
Authorization: `Token ${token}`,
},
})
.then(function (response) {
// console.log(response.data.results); // shows an array of JSON objects
return response.data.results; // I've also tried response.data.results.json()
})```
I just want the response returned as a variable that I can use to populate a FlatList component in RN.
const FlightListScreen = () => {
const [list, setList] = useState([]);
const flights = getFlights(); // currently returns as a promise object
Thank you for your help.
I think you have to store the response object directly to the json method. And then with that response you can store it to the variable
.then(response => { return response.json() })
.then(response => {
this.setState({
list: response
})
you are sending token without a bearer. Concrete your token with bearer like this
headers: {
Authorization: "Bearer " + token,
},
and another thing is your response class are not right this should be like this
.then((response) => response.json())
.then((responseJson) => {
API will Resopne here....
}
this is a complete example to call API with Token
fetch("/api/flights/", {
method: "GET",
headers: {
Authorization: "Bearer " + token,
},
})
.then((response) => response.json())
.then((responseJson) => {
console.log(responseJson);
setState(responseJson.VAlue);
})
.catch((error) => {
alert(error);
});
I am hitting an api and saving response in a variable but the variable in which i am storing is showing undefined by debugger.
try {
let response = await fetch(
"http://test.kelltontech.net/eventengine/getmyevents?hash=****×tamp=****&id=****",
{
method: "GET",
headers: {
"Content-Type": "application/json"
}
}
);
let responseJson = await response.json();
this.agendaDetails = await responseJson;
} catch (error) {
alert(error);
}
Here responseJson has data but not storing in agenda detail that is declared outside the main class like this agendaDetails={}
As an aside, and perhaps a better long term solution; instead of using fetch and wrapping it in a promise and making a tweak to return json. Use axios. It has promise support as standard and returns and expects json output.
let result = {};
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
result = response.data;
})
.catch(function (error) {
console.log(error);
});
Here is the link axios
you should use fetch with .then() to get response in json then assign that response to the variable just like below
fetch(URL.apiUrlUploadImages, {
method: "POST",
headers: {
Accept: 'application/json',
'Authorization': 'Bearer ' + this.token,
'Content-Type': 'application/json',
},
body: JSON.stringify({
"front_image": this.frontImageData
})
})
.then((response) => response.json())
.then((responseData) => {
var result = responseData});
I'm using react js and I want to post text and return a text.
Can anyone help me in posting text and receiving text? I have used
content type text/plain but that didn't help.
Is there any way to do?
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response)
.then(data => {
console.log(data)
this.setState({
code: data
});
});
This is what I have tried to get the text value from api
I am getting an error as
Uncaught promise typeError failed to fetch
fetch returns a "promise" for a Response object which has promise creators for json, text, etc. depending on the content type. So the code should be changed to.
Also consider adding a catch block for the promise in case of errors and check the console output error (if any ).
const options = {
method: "POST",
headers: {
"Content-Type": "text/plain"
},
body: this.state.url
}
fetch("http://localhost:3000/messages", options)
.then(response => response.json()) // or response.text()
.then(data => {
console.log(data)
this.setState({
code: data
});
})
.catch(err => { console.log('error while fetching', err) });
I need to return the result of a function from another page in react native which performing a fetch call. I use the method as follows. As I know this is because asynchronous call. Is there a special way to achieve this in react native ?
fetchcall.js
import address from '../actions/address'
const dashboard = {
getvals(){
return fetch(address.dashboardStats(),
{method: "POST",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify( {...
}),
})
.then((response) => response.json())
.then((responseData) => {
console.warn(responseData);
return responseData;
})
.catch((error) => { console.warn(error); })
.done();
// return 'test_val'';
}
}
export default dashboard;
dashboard.js
import dashboard from '../../services/dashboard';
class Dashboard extends Component {
componentDidMount(){
console.warn(dashboard.getvals());
}
}
export default connect(mapStateToProps, bindAction)(Dashboard);
Its display the result as "undefined", but that fetch call works and it displays the result. Any suggestion?
In fetchcall.js you are returning a Promise. Also since you are returning the responseData in the .then() method itself, you don't need the .done() method.
Since getvals() is returning a Promise, you need to access it's value in a .then() method.
Overall, your code should be like this:
function getvals(){
return fetch('https://jsonplaceholder.typicode.com/posts',
{
method: "GET",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
})
.then((response) => response.json())
.then((responseData) => {
console.log(responseData);
return responseData;
})
.catch(error => console.warn(error));
}
getvals().then(response => console.log(response));
The best architectural pattern, I think, is to use a callback function, usually by writing in as an anonymous function.
///Component.js
my_service.login((data=>{
this.setState({body: data.body});
}));
////Service.js
export const login = function (cb){
fetch('http://myapi.com/103?_format=hal_json')
.then((response) =>{
return response.json();
})
.then((data) =>{
cb(data);
});
}
I am still a junior developer, but use this pattern frequently. If someone has a reason for a different approach, I would love to hear it.
fetch always return a Promise doesn't matter what you are returning.
so you can return a string, variable or something else but you have to use .then to access data
file where you make fetch request
export const graphql = () => {
return fetch("https://graphqlzero.almansi.me/api", {
"method": "POST",
"headers": { "content-type": "application/json" },
"body": JSON.stringify({
query: `{
user(id: 1) {
id
name
}
}`
})
})
.then((res) => res.json()).then((responseData) => {
console.log(responseData);
return responseData;
})
}
file where you call function
graphql()
.then((e) => {
console.log("data", e)
});