Fetch wrapper for succinct Fetch API calls











up vote
0
down vote

favorite












For a while now I've been looking for a way to make Fetch calls from a React component in a succinct way, while still handling errors and exceptions.



I came up with the below



Fetch helper:



const getHeaders = () => ({ 'Content-Type': 'application/json' })

function handleErrors(response) {
if (!response.ok) {
let err = new Error('something went wrong!')
throw err
}
return response
}

function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null
}
return response.json()
}

export const get = (url, returnError = false) => {
return fetch(url, { headers: getHeaders() })
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}

export const post = (url, data, returnError = false) => {
return fetch(url, {
headers: getHeaders(),
body: data,
})
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}


Component use case #1 - I just want to know if I got data or not:



import { get } from './fetch-helper'

class UserDetail extends React.Component {
state = { user: null }

componentDidMount() {
get('/api/user')
.then(res => this.setState({ user: res }))
}

render() {
return (
<div>
{this.state.user &&
<div>
{user.username}<br />
{user.email_address}<br />
{user.phone_number}<br />
</div>}
</div>
)
}
}


Component use case #2 - I want to handle my errors in my component:



import { post } from './fetch-helper'

class LoginForm extends React.Component {
state = {
email: '',
emailError: null,
password: '',
passwordError: null,
}

handleSubmit = (e) => {
e.preventDefault()
post('/login', {
email: this.state.email, password: this.state.password
},
true // the critical part - passing true to post helper
).then(res => {
if (res.errors) {
Object.keys(res.errors).forEach(err =>
this.setState({ [`${err}Error`]: res.errors[err] })
)
}
})
}

change = (e) => this.setState({ [e.target.name]: e.target.value })

render() {
const { email, emailError, password, passwordError } = this.state
return (
<form onSubmit={this.handleSubmit}>
<input name="email" value={email} onChange={this.change} />
{emailError && <div>{emailError}</div>}
<input name="password" value={password} onChange={this.change} />
{passwordError && <div>{passwordError}</div>}
</form>
)
}
}


The critical part is passing true or false to the get or post helper. I.e, in a component where I just want to either display data or not, the fetch call handles errors itself, but if I pass true to post then I want to get errors back and handle them in the component.



Note: The components are pseudo code, since I have HOCs for inputs and a great deal of additional code for styling, labels, accessibility, etc. The fetch helper code is actual code I'm trying to develop and improve.










share|improve this question









New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
    – 200_success
    2 days ago










  • I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
    – Toby
    yesterday















up vote
0
down vote

favorite












For a while now I've been looking for a way to make Fetch calls from a React component in a succinct way, while still handling errors and exceptions.



I came up with the below



Fetch helper:



const getHeaders = () => ({ 'Content-Type': 'application/json' })

function handleErrors(response) {
if (!response.ok) {
let err = new Error('something went wrong!')
throw err
}
return response
}

function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null
}
return response.json()
}

export const get = (url, returnError = false) => {
return fetch(url, { headers: getHeaders() })
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}

export const post = (url, data, returnError = false) => {
return fetch(url, {
headers: getHeaders(),
body: data,
})
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}


Component use case #1 - I just want to know if I got data or not:



import { get } from './fetch-helper'

class UserDetail extends React.Component {
state = { user: null }

componentDidMount() {
get('/api/user')
.then(res => this.setState({ user: res }))
}

render() {
return (
<div>
{this.state.user &&
<div>
{user.username}<br />
{user.email_address}<br />
{user.phone_number}<br />
</div>}
</div>
)
}
}


Component use case #2 - I want to handle my errors in my component:



import { post } from './fetch-helper'

class LoginForm extends React.Component {
state = {
email: '',
emailError: null,
password: '',
passwordError: null,
}

handleSubmit = (e) => {
e.preventDefault()
post('/login', {
email: this.state.email, password: this.state.password
},
true // the critical part - passing true to post helper
).then(res => {
if (res.errors) {
Object.keys(res.errors).forEach(err =>
this.setState({ [`${err}Error`]: res.errors[err] })
)
}
})
}

change = (e) => this.setState({ [e.target.name]: e.target.value })

render() {
const { email, emailError, password, passwordError } = this.state
return (
<form onSubmit={this.handleSubmit}>
<input name="email" value={email} onChange={this.change} />
{emailError && <div>{emailError}</div>}
<input name="password" value={password} onChange={this.change} />
{passwordError && <div>{passwordError}</div>}
</form>
)
}
}


The critical part is passing true or false to the get or post helper. I.e, in a component where I just want to either display data or not, the fetch call handles errors itself, but if I pass true to post then I want to get errors back and handle them in the component.



Note: The components are pseudo code, since I have HOCs for inputs and a great deal of additional code for styling, labels, accessibility, etc. The fetch helper code is actual code I'm trying to develop and improve.










share|improve this question









New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
















  • 2




    Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
    – 200_success
    2 days ago










  • I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
    – Toby
    yesterday













up vote
0
down vote

favorite









up vote
0
down vote

favorite











For a while now I've been looking for a way to make Fetch calls from a React component in a succinct way, while still handling errors and exceptions.



I came up with the below



Fetch helper:



const getHeaders = () => ({ 'Content-Type': 'application/json' })

function handleErrors(response) {
if (!response.ok) {
let err = new Error('something went wrong!')
throw err
}
return response
}

function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null
}
return response.json()
}

export const get = (url, returnError = false) => {
return fetch(url, { headers: getHeaders() })
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}

export const post = (url, data, returnError = false) => {
return fetch(url, {
headers: getHeaders(),
body: data,
})
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}


Component use case #1 - I just want to know if I got data or not:



import { get } from './fetch-helper'

class UserDetail extends React.Component {
state = { user: null }

componentDidMount() {
get('/api/user')
.then(res => this.setState({ user: res }))
}

render() {
return (
<div>
{this.state.user &&
<div>
{user.username}<br />
{user.email_address}<br />
{user.phone_number}<br />
</div>}
</div>
)
}
}


Component use case #2 - I want to handle my errors in my component:



import { post } from './fetch-helper'

class LoginForm extends React.Component {
state = {
email: '',
emailError: null,
password: '',
passwordError: null,
}

handleSubmit = (e) => {
e.preventDefault()
post('/login', {
email: this.state.email, password: this.state.password
},
true // the critical part - passing true to post helper
).then(res => {
if (res.errors) {
Object.keys(res.errors).forEach(err =>
this.setState({ [`${err}Error`]: res.errors[err] })
)
}
})
}

change = (e) => this.setState({ [e.target.name]: e.target.value })

render() {
const { email, emailError, password, passwordError } = this.state
return (
<form onSubmit={this.handleSubmit}>
<input name="email" value={email} onChange={this.change} />
{emailError && <div>{emailError}</div>}
<input name="password" value={password} onChange={this.change} />
{passwordError && <div>{passwordError}</div>}
</form>
)
}
}


The critical part is passing true or false to the get or post helper. I.e, in a component where I just want to either display data or not, the fetch call handles errors itself, but if I pass true to post then I want to get errors back and handle them in the component.



Note: The components are pseudo code, since I have HOCs for inputs and a great deal of additional code for styling, labels, accessibility, etc. The fetch helper code is actual code I'm trying to develop and improve.










share|improve this question









New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











For a while now I've been looking for a way to make Fetch calls from a React component in a succinct way, while still handling errors and exceptions.



I came up with the below



Fetch helper:



const getHeaders = () => ({ 'Content-Type': 'application/json' })

function handleErrors(response) {
if (!response.ok) {
let err = new Error('something went wrong!')
throw err
}
return response
}

function parseJSON(response) {
if (response.status === 204 || response.status === 205) {
return null
}
return response.json()
}

export const get = (url, returnError = false) => {
return fetch(url, { headers: getHeaders() })
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}

export const post = (url, data, returnError = false) => {
return fetch(url, {
headers: getHeaders(),
body: data,
})
.then(handleErrors)
.then(parseJSON)
.catch(error => {
if (returnError) return error
})
}


Component use case #1 - I just want to know if I got data or not:



import { get } from './fetch-helper'

class UserDetail extends React.Component {
state = { user: null }

componentDidMount() {
get('/api/user')
.then(res => this.setState({ user: res }))
}

render() {
return (
<div>
{this.state.user &&
<div>
{user.username}<br />
{user.email_address}<br />
{user.phone_number}<br />
</div>}
</div>
)
}
}


Component use case #2 - I want to handle my errors in my component:



import { post } from './fetch-helper'

class LoginForm extends React.Component {
state = {
email: '',
emailError: null,
password: '',
passwordError: null,
}

handleSubmit = (e) => {
e.preventDefault()
post('/login', {
email: this.state.email, password: this.state.password
},
true // the critical part - passing true to post helper
).then(res => {
if (res.errors) {
Object.keys(res.errors).forEach(err =>
this.setState({ [`${err}Error`]: res.errors[err] })
)
}
})
}

change = (e) => this.setState({ [e.target.name]: e.target.value })

render() {
const { email, emailError, password, passwordError } = this.state
return (
<form onSubmit={this.handleSubmit}>
<input name="email" value={email} onChange={this.change} />
{emailError && <div>{emailError}</div>}
<input name="password" value={password} onChange={this.change} />
{passwordError && <div>{passwordError}</div>}
</form>
)
}
}


The critical part is passing true or false to the get or post helper. I.e, in a component where I just want to either display data or not, the fetch call handles errors itself, but if I pass true to post then I want to get errors back and handle them in the component.



Note: The components are pseudo code, since I have HOCs for inputs and a great deal of additional code for styling, labels, accessibility, etc. The fetch helper code is actual code I'm trying to develop and improve.







error-handling api ajax react.js jsx






share|improve this question









New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.











share|improve this question









New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









share|improve this question




share|improve this question








edited yesterday









200_success

127k15148412




127k15148412






New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.









asked 2 days ago









Toby

1042




1042




New contributor




Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.





New contributor





Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.






Toby is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.








  • 2




    Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
    – 200_success
    2 days ago










  • I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
    – Toby
    yesterday














  • 2




    Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
    – 200_success
    2 days ago










  • I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
    – Toby
    yesterday








2




2




Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
– 200_success
2 days ago




Welcome to Code Review. We can only review concrete code here, not generalized or obfuscated code. See the help center and How to Ask.
– 200_success
2 days ago












I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
– Toby
yesterday




I've extended the code in the question to make it more complete - please note that the components are pseudo code, the fetch helper code is what I'm trying to develop further.
– Toby
yesterday















active

oldest

votes











Your Answer





StackExchange.ifUsing("editor", function () {
return StackExchange.using("mathjaxEditing", function () {
StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
});
});
}, "mathjax-editing");

StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");

StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "196"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});

function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});


}
});






Toby is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208739%2ffetch-wrapper-for-succinct-fetch-api-calls%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown






























active

oldest

votes













active

oldest

votes









active

oldest

votes






active

oldest

votes








Toby is a new contributor. Be nice, and check out our Code of Conduct.










draft saved

draft discarded


















Toby is a new contributor. Be nice, and check out our Code of Conduct.













Toby is a new contributor. Be nice, and check out our Code of Conduct.












Toby is a new contributor. Be nice, and check out our Code of Conduct.
















Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid



  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f208739%2ffetch-wrapper-for-succinct-fetch-api-calls%23new-answer', 'question_page');
}
);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Ellipse (mathématiques)

Quarter-circle Tiles

Mont Emei