assist with fetch function in reactjs - javascript

Hello: i am trying to do a fetch to an endpoint in a react component. The fetch i have is working (all console logs show it is working). since this a function so i can reuse it - i want to return something from it. i tried returning the response but i dont think i have my return in the right place or something else is wrong. here is the log i am referring to:
console.log(response)
and here is the full code:
const doFetch = (fetchUri) => {
fetch(fetchUri)
.then(async response => {
const data = await response.json();
// check for error response
if (!response.ok) {
// get error message from body or default to response statusText
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
console.log('running fetch')
console.log(response)
console.log('showing data from fetch')
console.log(data)
return(response)
// this.setState({ totalReactPackages: data.total })
})
.catch(error => {
this.setState({ errorMessage: error.toString() });
console.error('There was an error!', error);
});
};
So I am hoping someone can help me do that 'return' properly. Thanks! Gerard

you did returned properly inside fetch but you did not returned fetch itself :)
const doFetch = (fetchUri) => {
return fetch(fetchUri)
.then(async response => {
const data = await response.json();
// check for error response
if (!response.ok) {
// get error message from body or default to response statusText
const error = (data && data.message) || response.statusText;
return Promise.reject(error);
}
console.log('running fetch')
console.log(response)
console.log('showing data from fetch')
console.log(data)
return (response)
// this.setState({ totalReactPackages: data.total })
})
.catch(error => {
this.setState({errorMessage: error.toString()});
console.error('There was an error!', error);
});
};
doFetch('randomurl').then(parsedAndPreparedResponse => this.setState({ data: parsedAndPreparedResponse }))

As Michal pointed out in his answer, you're only returning within the fetch, not from doFetch itself.
But to extend a little
The async/await within the then() is unnecessary since no asynchronous call is being made within it. The callback in then() will be run when the fetch promise is resolved.
So either get rid of the async/await or change your code to only use async/await.
If you do it could look something like this:
const doFetch = async fetchUri => {
try {
const response = await fetch(fetchUri)
// check for error response
if (!response.ok) {
throw new Error({
status: response.status,
statusText: response.statusText
});
}
// On successful call
const data = response.json();
// Return the data
return data();
} catch (error) {
// Error handling
}
};
You can call the function like this:
// Using the await keyword
const response = await doFetch(/* your fetchUri */);
// Using .then()
// The callback function in then() will run when the promise from
// doFetch() is resolved
doFetch(/* your fetchUri */).then(res => {
// Whatever you want to do with the response
});
Remember that in order you use the await keyword you need to be inside an async function.
const anAsyncFunction = async () => {
const response = await doFetch(/* your fetchUri */);
}

Related

Javascript fetch api use custom error message

I'm looking for a way of handling errors with the native javascript fetch api. Used to use jQuery, but I'm trying to use more native javascript functions.
I found this blog and like the approach: https://learnwithparam.com/blog/how-to-handle-fetch-errors/
fetch(url)
.then((response) => {
if (response.status >= 200 && response.status <= 299) {
return response.json();
}
throw Error(response.statusText);
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});
However, in the catch I'm getting the statusText that belongs to the HTTP code. For 400 for example Bad request. But that is not wat I want, my call to the server will respond with exactly what is wrong. So I want to use the response body text as a the error. I tried different ways, but I can't get the response body incase the HTTP code is 400. With jQuery I used response.responseJSON.html. But this is not available with the fetch api.
So how can I can use the response body as error code.
The fetch API was designed to work best with async functions. If you can make your outer function async, your code would become:
try {
const response = await fetch(url);
if (!response.ok) {
const text = await response.text();
throw Error(text);
}
const jsonResponse = await response.json();
// do whatever you want with the JSON response
} catch (error) {
console.log(error);
}
Otherwise, it gets a bit more complicated:
fetch(url)
.then((response) => {
if (response.ok) {
return response.json();
}
return response.text().then((text) => throw Error(text));
})
.then((jsonResponse) => {
// do whatever you want with the JSON response
}).catch((error) => {
// Handle the error
console.log(error);
});

get response.status in .then in Java Script

I tried to check if the status of my request is 200 (OK), but I do not know how to do these things together because the first and second .then, are not "like each other":
function f(path) {
await fetch(path)
.then(response => {
// console.log(response.status);
if (response.status != 200) {
throw response.status;
} else {
// do something
}
})
.then(response => response.json())
.then(...method for the response.json()...)
.catch(error => {
// print some error message
}
}
The second then failed and returned error.
I have a problem when I throw that.
It prints to the error to the console (when I check by changing the path to wrong path and I want to see if I treat errors).
what can I do?
You're checking it correctly in your first fulfillment handler (then callback), although I'd just use !response.ok. You don't usually need the status in the subsequent handlers.
But the problem with your first fulfillment handler is that it's not returning anything, so the subsequent fulfillment handler only sees undefined. Instead, return the promise from json():
function f(path) {
fetch(path)
.then(response => {
if (!response.ok) {
// Note: Strongly recommend using Error for exceptions/rejections
throw new Error("HTTP error " + response.status);
}
return response.json();
})
.then(data => {
// ...use the data here...
})
.catch(error => {
// ...show/handle error here...
});
}
Note that you can't use await in a traditional function, only in an async function. But you don't need it if you're using .then and .catch. I've removed it above.
If for some reason you wanted the status in subsequent fulfillment handlers, you'd have to return it from the first fulfillment handler. For instance:
function f(path) {
fetch(path)
.then(response => {
if (!response.ok) {
// Note: Strongly recommend using Error for exceptions/rejections
throw new Error("HTTP error " + response.status);
}
return response.json().then(data => ({status: response.status, data}));
})
.then(({status, data}) => {
// ...use `status` and `data` here...
})
.catch(error => {
// ...show/handle error here...
});
}
In that, I've used a nested fulfillment handler on the promise from json(), and then returned an object with status and data on it.
You need to return in your then chain, which at a glance appears to be one too many. Check out the following example...
fetch(path)
.then(r => r.ok ? r.json() : Promise.reject('oops')) // .statusText, etc
.then(r => {
// [...]
})
.catch(e => console.error(e)); // oops
a) I don't think you need await keyword since you're using .then() chaining.
b) You have to return something from the first then so as to get that in the next .then()
function f(path) {
await fetch(path)
.then(response => {
// console.log(response.status);
if (response.status != 200) {
throw response.status;
} else {
// do something
// After doing what you need return the response
return response
}
})
.then(response => response.json())
.then(...method for the response.json()...)
.catch(error => {
// print some error message
}
}
Actually, it's not clear what your function has to do. But I think your sturggle comes from not fully understanding how promises chain works. For that, I'd recommend familiarizing yourself with this article, it helped me a lot :)
So back to your function. The elegant solution is adding simple "tap" function, that allows you to do some stuff with current response, but still it passes response further for other .then chains.
Here's the tap function:
const tap = (callback) => (value) => (callback(value), value);
And finally how you can use it:
function f(path) {
fetch(path)
.then(
tap((response) => {
if (response.status !== 200) throw new Error(response.status);
})
)
.then((response) => {
// do other stuff
})
.catch((error) => console.error(error));
}
The number of browsers that support fetch but don't support async/await is now very small, so you may be better off using this simpler syntax first, and then transpiling for legacy browsers along with your shims for fetch.
Your function becomes:
try {
const response = await fetch(path);
// console.log(response.status);
if (response.status != 200) {
throw response.status;
} else {
// do something
}
const parsed = await response.json();
// do something with parsed
}
catch(error) {
// print some error message
}
This new syntax makes it much easier to deal with errors in the different then actions:
const response = await fetch(path);
// console.log(response.status);
if (response.status != 200) {
throw response.status;
} else {
// do something
}
let parsed; // Will hold the parsed JSON
try {
parsed = await response.json();
}
catch(error) {
// Deal with parsing errors
}
try {
// do something with parsed
}
catch(error) {
// Deal with errors using the parsed result
}

fetch api throws uncaught in promise error

I have a wrapper function for the fetch api to fetch different endpoints to my api but somehow it keeps complaining that there is unhandled rejection TypeError: Cannot read property 'catch' of undefined
const apiRequest = (url) => {
return fetch()
.then(async resp =>{
const json = await resp.json()
if(json.status == "success") return json
return Promise.reject('err')
})
.catch(err => {
return Promise.reject(err)
})
}
calling the function like:
apiRequest('/test')
.then(data => console.log(data))
.catch(err => console.log(err))
what am I doing wrong?
Note: When this answer was posted, the question didn't have the return. The OP added it afterward, claiming it was in their original code. But they also accepted the answer, so something below must have helped... :-)
apiRequest needs to return the promise chain. Right now, it doesn't, so calling it returns undefined.
const apiRequest = (url) => {
return fetch(url) // *** Note: Added `url` here
// ^−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−−
.then(async resp =>{
const json = await resp.json()
if(json.status == "success") return json
return Promise.reject('err')
})
.catch(err => {
return Promise.reject(err)
})
}
But, three things:
There's no point whatsoever to that catch handler; and
You need to check for response success before calling json; and
There's no reason for that then handler to be an async function.
Instead:
const apiRequest = (url) => {
return fetch(url) // *** Note: Added `url` here
.then(resp => {
if (!resp.ok) {
throw new Error("HTTP status " + resp.status);
}
return resp.json();
})
};
(I've also added some missing semicolons there, but if you prefer to rely on ASI, just leave them off.)
If the fetch promise is rejected, that rejection will be carried through to the promise from apiRequest for the caller to handle. If the fetch promise is fulfilled but resp.ok is false (because there was an HTTP level error like a 404 or 500), the promise from apiRequest will be rejected with the error thrown in the then handler. If those things work but the json call fails, the promise from apiRequest will be rejected with the error from json. Otherwise, the promise from apiRequest will be fulfilled with the parsed data.
It can also be a concise form arrow function if you prefer:
const apiRequest = (url) => fetch(url).then(resp => { // *** Note: Added `url` to `fetch` call
if (!resp.ok) {
throw new Error("HTTP status " + resp.status);
}
return resp.json();
});
Your original code used an async function in then. If you can ues async functions in your environment, you may prefer to make apiRequest an async function:
const apiRequest = async (url) => {
const resp = await fetch(url); // *** Note: Added `url` here
if (!resp.ok) {
throw new Error("HTTP status " + resp.status);
}
return resp.json();
};

How to store a Promise's resolve into a variable using Fetch (not ajax)

The following code works well and logs to the console a fetch from a website (that outputs a simple file already in json format):
getData = url => {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return; //returns undefined!
}
// Examine the text in the response
response.json().then(data => {
console.log(data);
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
});
};
getData(urlToFetch); // logs to console the website call: a json file
I want to store that fetch's content values in a variable for later use.
So, when I change:
console.log(data);
to:
return data;
I get an undefined. Any help?
Because you .catch in your getData function if something else goes wrong your function will resolve undefined as well. If you want to log it then you need to return the error as a rejecting promise so the caller can handle the error and not get an undefined value for data when the promise resolves.
You can return Promise.reject("no 200 status code") for rejecting and return response.json() for resolve If you want to add .then(x=>console.log(x)) you still need to return something or the thing calling getData will resolve to undefined:
getData = url => {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return Promise.reject(//reject by returning a rejecting promise
"Looks like there was a problem. Status Code: " + response.status
);
}
// Examine the text in the response
response.json().then(data => {
console.log(data);
return data;//still need to return the data here
});
})
.catch(function (err) {
console.log("Fetch Error :-S", err);
//return the reject again so the caller knows something went wrong
return Promise.reject(err);
});
};
getData(urlToFetch) // logs to console the website call: a json file
.then(
x=>console.log("caller got data:",x)
)
.catch(
e=>console.log("caller got error:",e)
);
You could use ES6 async-await to get this done easily:
Using async-await, your code will look like this:
function getData(url){
return new Promise((resolve, reject) => {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
return; //returns undefined!
}
// Examine the text in the response
response.json().then(data => {
resolve(data);
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
reject(err)
});
})
}
// Then call the function like so:
async function useData(){
const data = await getData(urlToFetch);
// console.log(data) ===> result;
}
return; //returns undefined!
You aren't returning anything, so return by itself returns undefined unless you supply it with a value.
You need to store the promise and when you need a value, you will have to resolve it. I would change this:
// Examine the text in the response
response.json().then(data => {
console.log(data);
});
to this:
// Examine the text in the response
return response.json();
Then call getData and either resolve the promise:
getData(urlToFetch).then(data => {
// Code to use data
})
Or store the promise in the variable and use it later:
let result = getData(urlToFetch);
result.then(data => {
// so whatever with data
});
What happens here is, you are under then block. Your getData functions returns the data as soon as it call fetch. It doesn't wait for the async fetch opertion to receive callback and then call function inside then.
So the return inside then function have nothing to return to. That's why it doesn't work.
Instead you can return a promise from the getData function and call then on it to get the data. I faced a similar issue sometime ago.
An example: (not tested)
getData = url => {
new Promise(function (resolve, reject) {
fetch(url)
.then(response => {
if (response.status !== 200) {
console.log(
"Looks like there was a problem. Status Code: " + response.status
);
reject(); //returns undefined!
}
// Examine the text in the response
response.json().then(data => {
resolve(data);
});
})
.catch(function(err) {
console.log("Fetch Error :-S", err);
});
};
};
getData(urlToFetch).then(data => /*do something*/ ); // logs to console the website call: a json file
So when the data is available, you can call resolve(data) and it will invoke then method on your promise.
Hope it helps.

How to include both a parsed response and original response headers in fetch errors [duplicate]

This question already has answers here:
How do I access previous promise results in a .then() chain?
(17 answers)
Closed 6 years ago.
I have the following promise chain:
return fetch(request)
.then(checkStatus)
.then(response => response.json())
.then(json => ({ response: json }))
.catch(error => ({ error }))
Where checkstatus() checks if the request was successful, and returns an error if it wasn't. This error will be caught and returned. But, the problem is that I want to add the both response.statusText and the results of response.json() to the error. The problem is that when I parse it I lose the original response in the chain since I have to return response.json() because it's a promise.
This is what checkstatus does currently:
const checkStatus = response => {
if (response.ok) return response
const error = new Error('Response is not ok')
// this works because the response hasn't been parsed yet
if (response.statusText) error.message = response.statusText
// an error response from our api will include errors, but these are
// not available here since response.json() hasn't been called
if (response.errors) error.errors = response.errors
throw error
}
export default checkStatus
How do I return an error with error.message = response.statusText and error.errors = response.json().errors?
Here's my helper for sane fetch error handling, fetchOk:
let fetchOk = (...args) => fetch(...args)
.then(res => res.ok ? res : res.json().then(data => {
throw Object.assign(new Error(data.error_message), {name: res.statusText});
}));
Which I then substitute for fetch.
let fetchOk = (...args) => fetch(...args)
.then(res => res.ok ? res : res.json().then(data => {
throw Object.assign(new Error(data.error_message), {name: res.statusText});
}));
fetchOk("https://api.stackexchange.com/2.2/blah")
.then(response => response.json())
.catch(e => console.log(e)); // Bad Request: no method found with this name
var console = { log: msg => div.innerHTML += msg + "<br>" };
<div id="div"></div>
It doesn't load the data unless there's an error, making it a direct replacement.
I use the new async/await syntax, since that reads in a more intuitive way:
async fetchData(request) {
try {
const response = await fetch(request)
const data = await response.json()
// return the data if the response was ok
if (response.ok) return { data }
// otherwise return an error with the error data
const error = new Error(response.statusText)
if (data.errors) error.errors = data.errors
throw error
} catch (error) {
return { error }
}
}
It makes it very easy to handle both the promise that fetch returns as well as the promise that response.json() returns.

Categories