Skip to content

Instantly share code, notes, and snippets.

@droidMakk
Created September 14, 2019 13:00
Show Gist options
  • Save droidMakk/f3585b3790b3216f2a0b646b2954a3f2 to your computer and use it in GitHub Desktop.
Save droidMakk/f3585b3790b3216f2a0b646b2954a3f2 to your computer and use it in GitHub Desktop.
So this gist contains a hook to make network request and recieves the config from a NetworkConfig context. Make sure to wrap your app around the context when you start using this.
import React from 'react';
// Either use a config file or env file
import { API_URL, HOME_PAGE_URL } from '../config';
const initialCtx = {
NetworkCtx: {
apiUrl: API_URL, token: null, homePage: HOME_PAGE_URL
},
setNetworkCtx: () => null
}
export const NetworkContext = React.createContext(initialCtx);
export const NetworkConsumer = NetworkContext.Consumer;
export const NetworkProvider = (props) => {
const [NetworkCtx, setNetworkCtx] = React.useState(initialCtx.NetworkCtx);
return (
<NetworkContext.Provider value={{ NetworkCtx, setNetworkCtx }} >
{props.children}
</NetworkContext.Provider>
)
};
// HOOK which sends the network request
export const useNetworkRequest = (url: string, body: string | object | null = null, mapper: ({ }) => Promise<{}> = null) => {
const { NetworkCtx: { apiUrl } } = React.useContext(NetworkContext);
const [loading, setLoading] = React.useState(false);
const [error, setError] = React.useState(false);
const [data, setData] = React.useState({});
const [mapped, setMapped] = React.useState({});
const [status, setStatus] = React.useState({ status: null, statusText: '' })
// PARSE FOR NETWORK REQUEST
const method = data ? 'POST' : 'GET';
url = `${apiUrl}${url}`
body = typeof body === "string" ? body : JSON.stringify(body);
React.useEffect(() => {
setLoading(true);
fetch(url, { method, body })
.then(res => {
setStatus({ status: res.status, statusText: res.statusText })
return res.json();
})
.then(resdata => {
setData(resdata);
setLoading(false);
if (mapper) {
mapper(resdata)
.then(mappeddata => setMapped(mappeddata))
.catch(err => setError(true));
}
})
.catch(err => {
setError(true);
setLoading(false);
});
}, [url, data, body, method, mapper]);
return { loading, error, status, data, mapped }
}
import React from 'react';
import RouteApp from './routes';
function App() {
return(
<NetworkProvider>
<RouteApp />
</NetworkProvider>
)
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment