Skip to content

Instantly share code, notes, and snippets.

@emiaj

emiaj/App.tsx Secret

Last active Jul 23, 2019
Embed
What would you like to do?
useEffect and fetch
import React from 'react';
import './App.css';
import { PopularFrameworks } from './PopularFrameworks';
const App: React.FC = () => {
return (
<div style={{ padding: '1rem' }}>
<h1>JS Frameworks</h1>
<PopularFrameworks />
</div>
);
}
export default App;
import React from 'react';
export const FrameworkDetails: React.FC<FrameworkDetailsProps> = (props: FrameworkDetailsProps) => {
const [state, update] = React.useState<FrameworkDetailsState>({ loaded: false });
React.useEffect(() => {
const controller = new AbortController();
update({ loaded: false, description: null });
fetch(props.details, { signal: controller.signal })
.then(response => response.json())
.then(json => update({ loaded: true, ...json }))
.catch(e => {
if (controller.signal.aborted) {
console.log('Request has been gracefully cancelled');
}
else {
throw e;
}
});
return function cancel() {
controller.abort();
};
}, [props.details]);
return <div style={{ padding: '1rem', margin: '1rem', flex: 1 }}>
{state.loaded ? <p>
{state.description}
</p> : <p>
Loading information...
</p>
}
</div>;
}
export interface FrameworkDetailsProps {
details: string;
}
export interface FrameworkDetailsState {
loaded: boolean;
description?: string | null;
}
import React from 'react';
import { FrameworkDetails } from './FrameworkDetails';
export const PopularFrameworks: React.FC = () => {
const [state, update] = React.useState<FrameworkSummary | null>(null);
const frameworks: FrameworkSummary[] = [
{ "name": "React", details: "http://www.mocky.io/v2/5d36894a56000067003a5323?mocky-delay=3s" },
{ "name": "Angular", details: "http://www.mocky.io/v2/5d368a3256000054003a5327?mocky-delay=2s" },
{ "name": "Vue", details: "http://www.mocky.io/v2/5d36899b5600007d5d3a5324?mocky-delay=1s" }
];
return <div style={{ display: 'flex' }}>
<div style={{ flex: 1, display: 'flex' }}>
<ul style={{ listStyle: 'none', flex: 1 }}>
{
frameworks.map(framework => {
return <li key={framework.name}
style={state && state.name === framework.name ? selectedFrameworkStyle : frameworkStyle}
onClick={() => update(framework)}>
{framework.name}
</li>
})
}
</ul>
</div>
<div style={{ flex: 1, display: 'flex' }}>
{
state &&
<FrameworkDetails {...state} />
}
</div>
</div>;
}
interface FrameworkSummary {
name: string;
details: string;
}
const frameworkStyle: React.CSSProperties = {
cursor: 'pointer',
borderWidth: 1,
borderColor: '#ccc',
borderStyle: 'solid',
margin: '1rem',
padding: '1rem'
}
const selectedFrameworkStyle: React.CSSProperties = {
...frameworkStyle,
backgroundColor: 'blue',
color: 'white',
fontWeight: 'bolder'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.