Skip to content

Instantly share code, notes, and snippets.

@andersondias
Created July 8, 2022 17:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersondias/4f199efd7239c7991141f0465af83d56 to your computer and use it in GitHub Desktop.
Save andersondias/4f199efd7239c7991141f0465af83d56 to your computer and use it in GitHub Desktop.
Basic useApi React hook
const express = require('express')
var cors = require('cors')
const app = express()
const port = 9000
app.use(cors())
function sleep (time) {
return new Promise((resolve) => setTimeout(resolve, time));
}
app.get('/success', (req, res) => {
res.json({ data: { message: 'Hello World!' }, errors: [] })
})
app.get('/error', (req, res) => {
sleep(500).then(() => {
res.json({ data: { message: 'Error' }, errors: [{ message: 'Error' }] })
});
})
app.listen(port, () => {
console.log(`Example app listening on port ${port}`)
})
import React from 'react'
function useApi(path) {
const api = `http://localhost:9000${path}`
const [state, setState] = React.useState({
loading: true,
data: null,
errors: null,
})
React.useEffect(() => {
setState({loading: true})
fetch(api)
.then(response => response.json())
.then(response => {
setState({
loading: false,
data: response.data,
errors: response.errors,
})
}).catch(error => {
setState({
loading: false,
data: null,
errors: error,
})
})
}, [api])
return {...state}
}
function App() {
const [path, setPath] = React.useState('/success')
const { loading, data, errors } = useApi(path)
if (loading) {
return <p>Loading data from {path}...</p>
}
return (
<>
<button onClick={e => setPath(path === '/success' ? '/error' : '/success')}>Toggle</button>
<p>Path: {path}</p>
<p>Data: {JSON.stringify(data)}</p>
<p>Errors: {JSON.stringify(errors)}</p>
</>
);
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment