Created
July 8, 2022 17:23
-
-
Save andersondias/4f199efd7239c7991141f0465af83d56 to your computer and use it in GitHub Desktop.
Basic useApi React hook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`) | |
}) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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