This commit is contained in:
2020-08-22 11:12:56 +02:00
parent 3f0f791dbe
commit 2824588e4f
11 changed files with 132 additions and 167 deletions

View File

@@ -1,87 +1,14 @@
import React, { useState, useEffect, createContext } from 'react';
import { Layout, Spin } from 'antd';
import React, { createContext } from 'react';
const data = require('../../data.json');
interface GithubContextType {
username: string;
user?: any;
keys?: string[];
error?: any;
state: 'loading' | 'ready' | 'failed'
}
interface Props {
username: string;
children: React.ReactNode;
}
const Loader = () => (
<Layout
style={{
position: 'fixed',
alignItems: 'center',
justifyContent: 'center',
height: '100%',
width: '100%',
}}
>
<Spin size="large" />
</Layout>
);
const GithubContext = createContext<GithubContextType>({
username: 'unknown',
state: 'failed',
});
const headers = {
};
const GithubProvider: React.FC<Props> = ({
username,
children,
}) => {
const [keys, setKeys] = useState<GithubContextType['keys'] | undefined>();
const [state, setState] = useState<GithubContextType['state']>('loading');
const [error, setError] = useState<GithubContextType['state'] | undefined>();
const [user, setUser] = useState<GithubContextType['user'] | undefined>();
useEffect(() => {
const run = async () => {
try {
const keysRes = await fetch(`https://api.github.com/users/${username}/gpg_keys`, { headers });
const userRes = await fetch(`https://api.github.com/users/${username}`, { headers });
const keys = await keysRes.json();
const user = await userRes.json();
setState('ready');
setKeys(keys.map((key: any) => key.raw_key));
setUser(user);
} catch (err) {
setState('failed');
setError(err);
}
};
run();
}, [username]);
if (state === 'loading') {
return <Loader />;
}
return (
<GithubContext.Provider
value={{
username,
user,
keys,
state,
error,
}}
>
{children}
</GithubContext.Provider>
);
};
const GithubContext = createContext<GithubContextType>(data);
const GithubProvider = GithubContext.Provider;
export {
GithubProvider,