Get response.data from fetch() as variable to use in React-Native - javascript

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

Related

How to access property of stringified JSON?

I have this code that sends me back an url and an error. I'm trying to access the url so I can navigate to it with router.
With this code:
const redirectToStripe = async () => {
const response = await fetch(
"http://localhost:5000/create-checkout-session",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(cartItems.value),
}
)
.then((response) => response.json())
.then((response) =>
console.log("stringied response", JSON.stringify(response))
);
const { url } = await response.json();
console.log("url=", url); <--------------Doesn't execute, no console.log() readout
// window.location.href = url;
// router.go(url) <------- NEED TO FIX THIS AND UNCOMMENT;
};
I get this error:
Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'json')
at redirectToStripe
and this console.log() readout:
stringied response {"url":"https://checkout.stripe.com/c/pay/cs_test_a1X3r92YtZfM9H"}
That is the url I'm trying to navigate to, but I don't know how to access it in this stringified form. How do I grab the value of "url" so I can put it in the function:
router.go(url)
The later "url" console.log() never executes because of the json error (pretty sure), but I'm guessing it's the same url as the stringified one above?
I also don't know why I'm getting that error or if it's even consequential and needs to be fixed because I'm already getting the url I need. Does the error have something to do with the "Content-Type" header? Did I pick the right one? Is it something else I'm doing wrong?
Also, this is what the backend endpoint looks like if it adds context or anything.
app.post("/create-checkout-session", async (req, res) => {
// Make an array of just our Stripe Price ID and quantities
const lineItems = req.body.map((item) => {
console.log("lineItems= ", item.item.priceId, item.item.quantity);
return {
price: item.item.priceId,
quantity: item.item.quantity,
};
});
const session = await stripe.checkout.sessions.create({
mode: "payment",
line_items: lineItems,
success_url: `http://localhost:8080/success?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `http://localhost:8080/`,
});
return res.send({ url: session.url });
});
EDITS
#pope_maverick
This code:
const redirectToStripe = () => {
const response = fetch("http://localhost:5000/create-checkout-session", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(cartItems.value),
}).then((response) => response.json());
const {url} = response.json();
// const { url } = await response.json();
console.log("url=", url);
gets me the error:
Uncaught TypeError: response.json is not a function
You forgot to return the response in your last .then callback. So your const response is actually void.
const response = await fetch(
"http://localhost:5000/create-checkout-session",
// [...]
)
.then((response) => response.json())
.then((response) => {
console.log("stringied response", JSON.stringify(response))
// โ—๏ธ Return `response` here, or the Promise will return the returned value of `console.log` which is `void`!
return response
});
You face this issue because the API returns a string not an object so you are suppsed to use Response.text() over Response.json(), have a look the MDN Response.text()
Try below:
const redirectToStripe = async () => {
const response = await fetch(
"http://localhost:5000/create-checkout-session",
{
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify(cartItems.value),
}
)
.then(response => response.text())
.then((url) => {
const { url } = url;
console.log("url=", url);
router.go(url)
})
.catch(err => console.log(err))
};

Getting API authentication key error with PublicAPI

I'm new to the FetchAPAI. For my first API project, I'm currently using the ClimatIQ API and following the steps in their Quickstart guide. Even if I've already signed up and received an authentication key from them, I keep getting the ff error from them:
POST https://beta2.api.climatiq.io/estimate 400
{error: 'invalid_request', message: 'Error parsing the request body.'}
Take note in the guide, the code is in Curl, and I did my best trying to convert that code into a fetchAPI request on JavaScript.
const fetchData = async (url) => {
await fetch(url, {
method: "POST",
headers: { Authorization: "Bearer MY_API_KEY" },
data: {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
},
//body: JSON.stringify(data),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");
From time to time, it also shows a "header is not defined" even if I already put in the authentication key they gave me in the "MY_API_KEY" part of my codebase. Is this an error with their server?
try this:
const data = {
emission_factor: "electricity-energy_source_grid_mix",
parameters: {
energy: 4200,
energy_unit: "kWh",
},
};
const fetchData = async(url) => {
await fetch(url, {
method: "POST",
headers: {
Authorization: "Bearer MY_API_KEY",
"Content-Type": "application/json"
},
body: JSON.stringify(data)
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((err) => console.log(`Here's the error ${err}`));
};
fetchData("https://beta2.api.climatiq.io/estimate");

Hooks and Api calling

I'm calling my API through AXIOS. My response is coming back, which i can see if i check my network, but it returns empty data when I console.log:
useEffect(() => {
async function bt() {
const authAxios = axios.create({
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
const Data = await authAxios
.get('/tasks/')
.then((res) => {
console.log(res);
})
.catch((e) => {
console.log(e);
});
}
bt();
}, []);
1 - You've used an async function alongside trying to resolve the promise. Either get rid of the async and await or get rid of everything after "await authAxios"(i.e the catch and then blocks)
2 - The reason why res.data console log is blank is because res.data is undefined try changing that line to just res. Check the response Object to see if the info is there.
.then((res) => {
//console.log(res.data);
console.log(res)
setmessage(res.data);
// this.getUserUpdate(res.data)
console.log(res.data);
})
For res.data to work you need to make sure that your API creates an attribute called data for the response. If this doesn't work I recommend you also add what your back-end looks like.
As #Pyro mentioned you are mixing up 2 completly different promise-handling techniques.
You'd have to decide to either use .then()๐Ÿ”— or async/await๐Ÿ”—
e.g.
With async/await:
useEffect(() => {
async function bt() {
const authAxios = axios.create({
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
const Data = await authAxios.get('/tasks/')
}
bt();
}, []);
Or with .then()
useEffect(() => {
function bt() {
const authAxios = axios.create({
headers: {
Authorization: `Bearer ${localStorage.getItem('token')}`,
},
});
const Data = authAxios.get('/tasks/').then(console.log).catch(console.log);
}
bt();
}, []);

Accessing promise data from Node API inside React fetch call

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

Node Fetch Post Request using Graphql Query

I'm trying to make a POST request with a GraphQL query, but it's returning the error Must provide query string, even though my request works in PostMan.
Here is how I have it running in PostMan:
And here is the code I'm running in my application:
const url = `http://localhost:3000/graphql`;
return fetch(url, {
method: 'POST',
Accept: 'api_version=2',
'Content-Type': 'application/graphql',
body: `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
Any ideas what I'm doing wrong? Is it possible to make it so that the body attribute I'm passing in with the fetch request is formatted as Text like I've specified in the PostMan request's body?
The body is expected to have a query property, containing the query string. Another variable property can be passed as well, to submit GraphQL variables for the query as well.
This should work in your case:
const url = `http://localhost:3000/graphql`;
const query = `
{
users(name: "Thomas") {
firstName
lastName
}
}
`
return fetch(url, {
method: 'POST',
Header: {
'Content-Type': 'application/graphql'
}
body: query
})
.then(response => response.json())
.then(data => {
console.log('Here is the data: ', data);
...
});
This is how to submit GraphQL variables:
const query = `
query movies($first: Int!) {
allMovies(first: $first) {
title
}
}
`
const variables = {
first: 3
}
return fetch('https://api.graph.cool/simple/v1/cixos23120m0n0173veiiwrjr', {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({query, variables})
})
.then(response => response.json())
.then(data => {
return data
})
.catch((e) => {
console.log(e)
})
I created a complete example on GitHub.

Categories