Get response headers object in redux with React.js - javascript

Using redux in React.js I get the most starred repositories in the last 30 days, now I wanna use the pagination that github api provides but to do so I have to use the headers in the response, how can I do that, how can I change my code to get the headers from the response, this is the function that gets the response:
import getDate from './getDate';
export function fetchRepos() {
return function(dispatch) {
dispatch({
type: "FETCH_REPOS_REQUEST",
});
return fetch(
"https://api.github.com/search/repositories?q=created:>" +
getDate() +
"&sort=stars&order=desc",
)
.then(response => response.json().then(body => ({response, body})))
.then(({response, body}) => {
if (!response.ok) {
dispatch({
type: "FETCH_REPOS_FAILURE",
error: body.error,
});
} else {
dispatch({
type: "FETCH_REPOS_SUCCESS",
repos: body.items,
});
}
});
};
}
Please help, thank you!

I like to assemble a response object that includes the headers as an object for fetch calls like so:
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => (res.headers.get('content-type').includes('json') ? res.json() : res.text())
.then(data => ({
headers: [...res.headers].reduce((acc, header) => {
return {...acc, [header[0]]: header[1]};
}, {}),
status: res.status,
data: data,
}))
.then(response => console.log(response)));
in your case you could then simply get the headers with response.headers in the last .then().
but technically you can access the headers with res.headers.get('<header.name>').

Related

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

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

Fetch Result Return with status code and json data

I have a fetch API call that calls API back end and in return, I will get the response object with status code. What I am trying to do is base on return, I wanted to return the JSON response with status code. so that other part of the javascript can manipulate base on status code. My fetch function is as follow.
I have tried with as follow below, but it returns as a given screenshot. It gives me promise value which I didn't want to get.
export const createUser = ( posts ) => {
const apiRoute= "/api/register";
return window.fetch(`${apiRoute}`, {
"headers": headers,
method: "POST",
body: JSON.stringify(posts)
}).then(response => ({
'status' : response.status,
'data' : response.json()
}))
.catch(error => console.error('Error: ', error))
;
}
I know that it might be the duplicate from this post (Fetch api - getting json body in both then and catch blocks for separate status codes), but I do not want my data to return as a promise. Instead, I wanted to return fully constructed well form JSON data.
Something like this.
{status: 400, data: {id:1,name:Hello World}}
how can i achieve this?
"It gives me promise value"
That's right, as per the documentation.
You need to resolve that promise before resolving the outer promise.
For example
.then(response => {
return response.json().then(data => ({
status: response.status,
data
}))
})
Alternatively, use an async function
export const createUser = async ( posts ) => {
const apiRoute= "/api/register";
try {
const response = await window.fetch(apiRoute, {
headers,
method: "POST",
body: JSON.stringify(posts)
})
return {
status: response.status,
data: await response.json()
}
} catch (error) {
console.error('Error: ', error)
throw error
}
}

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

Multiple API Calls in React

I am making an app where I receive data from an API. Once I get this data I want to make another call to the same API with the endpoint that I got from the first call.
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req)
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
})
})
this.setState(()=>{
return{
data: json
}
})
})
I am making two fetch requests here but the problem is the data from the first response is output after second fetch request. Also the state: data gets set before state: recipe and the components render with the data from state: data.
render(){
return(
<div className="my-container">
<EnterCalorie getData={this.getData}/>
<MealData data={this.state.data} recipe={this.state.recipe}/>
</div>
)
}
How can i make sure both get passed down at the same time?
In line 3 return return response.json() instead of nothing (undefined).
Update:
const toJson = response => response.json()
fetch(req)
.then(toJson)
.then(json => {
this.setState(() => {
return {
data: json
}
})
return json
})
.then((json) => {
console.log(json)
const promises = json.meals.map((obj) => {
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url, {
method: 'GET',
headers: header
})
return fetch(req)
.then(toJson)
.then((json) => {
console.log(json);
this.setState((prevState) => ({
recipe: prevState.recipe.push(json)
}))
})
})
return Promise.all(promises)
})
.then(() => {
console.log('job done')
})
You need to map your array into promises. Then use Promise.all to wait for them the get resolved.
There was parenthesis missing from:
this.setState((prevState)=>{
recipe: prevState.recipe.push(json)
})
A sidenote, this whole stuff should be refactored. You're not going to get far with this code style / code complexity.
fetch(req) // req no1
.then((response)=>(
response.json()
)).then((json)=>{
console.log(json)
json.meals.map((obj)=>{
let url = `https://spoonacular-recipe-food-nutrition-v1.p.mashape.com/recipes/${obj.id}/information`
let req = new Request(url,{
method: 'GET',
headers: header
})
fetch(req) // req no 1 called again
.then((response)=>(
response.json()
)).then((json1)=>{
console.log(json1);
this.setState((prevState)=>{
recipe: prevState.recipe.push(json1)
})
this.setState(()=>{
return{
data: json
})
})
})
})
})
I think you are calling api with same req parameters again in the second fetch call
This is a callback hell, please look for Promise races, and check the all() promise method.

extract both JSON and headers from fetch()

I am modelling the auth layer for a simple react/redux app. On the server side I have an API based on the devise_token_auth gem.
I am using fetch to post a sign in request:
const JSON_HEADERS = new Headers({
'Content-Type': 'application/json'
});
export const postLogin = ({ email, password }) => fetch(
`${API_ROOT}/v1/auth/sign_in`, {
method: 'POST',
headers: JSON_HEADERS,
body: JSON.stringify({ email, password })
});
// postLogin({ email: 'test#test.it', password: 'whatever' });
This works, and I get a 200 response and all the data I need. My problem is, information is divided between the response body and headers.
Body: user info
Headers: access-token, expiration, etc.
I could parse the JSON body this way:
postLogin({ 'test#test.it', password: 'whatever' })
.then(res => res.json())
.then(resJson => dispatch(myAction(resJson))
But then myAction would not get any data from the headers (lost while parsing JSON).
Is there a way to get both headers and body from a fetch Request?
Thanks!
I thought I'd share the way we finally solved this problem: by just adding a step in the .then chain (before parsing the JSON) to parse the auth headers and dispatch the proper action:
fetch('/some/url')
.then(res => {
const authHeaders = ['access-token', 'client', 'uid']
.reduce((result, key) => {
let val = res.headers.get(key);
if (val) {
result[key] = val;
}
}, {});
store.dispatch(doSomethingWith(authHeaders)); // or localStorage
return res;
})
.then(res => res.json())
.then(jsonResponse => doSomethingElseWith(jsonResponse))
One more approach, inspired by the mighty Dan Abramov (http://stackoverflow.com/a/37099629/1463770)
fetch('/some/url')
.then(res => res.json().then(json => ({
headers: res.headers,
status: res.status,
json
}))
.then({ headers, status, json } => goCrazyWith(headers, status, json));
HTH
Using async/await:
const res = await fetch('/url')
const json = await res.json()
doSomething(headers, json)
Without async/await:
fetch('/url')
.then( res => {
const headers = res.headers.raw())
return new Promise((resolve, reject) => {
res.json().then( json => resolve({headers, json}) )
})
})
.then( ({headers, json}) => doSomething(headers, json) )
This approach with Promise is more general. It is working in all cases, even when it is inconvenient to create a closure that captures res variable (as in the other answer here). For example when handlers is more complex and extracted (refactored) to separated functions.
My solution for the WP json API
fetch(getWPContent(searchTerm, page))
.then(response => response.json().then(json => ({
totalPages: response.headers.get("x-wp-totalpages"),
totalHits: response.headers.get("x-wp-total"),
json
})))
.then(result => {
console.log(result)
})
If you want to parse all headers into an object (rather than keeping the Iterator) you can do as follows (based on Dan Abramov's approach above):
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => (res.headers.get('content-type').includes('json') ? res.json() : res.text())
.then(data => ({
headers: [...res.headers].reduce((acc, header) => {
return {...acc, [header[0]]: header[1]};
}, {}),
status: res.status,
data: data,
}))
.then((headers, status, data) => console.log(headers, status, data)));
or within an async context/function:
let response = await fetch('https://jsonplaceholder.typicode.com/users');
const data = await (
response.headers.get('content-type').includes('json')
? response.json()
: response.text()
);
response = {
headers: [...response.headers].reduce((acc, header) => {
return {...acc, [header[0]]: header[1]};
}, {}),
status: response.status,
data: data,
};
will result in:
{
data: [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}],
headers: {
cache-control: "public, max-age=14400"
content-type: "application/json; charset=utf-8"
expires: "Sun, 23 Jun 2019 22:50:21 GMT"
pragma: "no-cache"
},
status: 200
}
depending on your use case this might be more convenient to use. This solution also takes into account the content-type to call either .json() or .text() on the response.

Categories