Skip to content

Instantly share code, notes, and snippets.

@troygoode
Last active January 2, 2019 05:39
Show Gist options
  • Save troygoode/348ee2bfce8e529658b6d1f3e4c146bb to your computer and use it in GitHub Desktop.
Save troygoode/348ee2bfce8e529658b6d1f3e4c146bb to your computer and use it in GitHub Desktop.
I <3 React Hooks
import React, { useState, useMemo } from 'react'
import { useInput } from 'react-hanger' // form binding hooks
import { usePromise } from 'react-hook-utils' // fetch/promise binding hooks
import { getJSON, postJSON } from './fetch-json'
const ExampleForm = ({ userId }) => {
// hooks!
const [user, errorLoadingUser, isLoadingUser] = usePromise(useMemo(
() => getJSON(`/api/users/${userId}`),
[userId] // memo-ize on userId; only re-fetch when the userId prop changes
))
const name = useInput(user.name)
const email = useInput(user.email)
const [validationError, setValidationError] = setState()
const onSubmit = async (ev) => {
try {
ev.preventDefault()
await postJSON(`/api/users/${userId}`, {
name: name.value,
email: email.value
})
} catch (e) {
setValidationError(e)
}
}
if (errorLoadingUser) {
return <div>An error occurred while fetching User #{userId}.</div>
} else if (isLoadingUser) {
return <div>Loading, please wait...</div>
} else {
return (
<form onSubmit={onSubmit}>
<h1>Update User #{userId}</h1>
{validationError && (
<div className="error">{validationError}</div>
)}
<input placeholder="Name" {...name.bindToInput} />
<input placeholder="Email" type="email" {...email.bindToInput} />
<button type="submit">Submit</button>
</form>
)
}
}
// using native browser fetch; just wrapping for clarity
export async function getJSON (url) {
return fetch(url).then(res => res.json())
}
// using native browser fetch; just wrapping for clarity
export async function postJSON (url, payload) {
return fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json, text/plain, */*',
'Content-Type': 'application/json'
},
body: JSON.stringify(payload)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment