Skip to content

Instantly share code, notes, and snippets.

@Jahans3
Last active November 9, 2021 15:44
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 Jahans3/020a54c96b0dbc4f2a92c4dffb936e0e to your computer and use it in GitHub Desktop.
Save Jahans3/020a54c96b0dbc4f2a92c4dffb936e0e to your computer and use it in GitHub Desktop.
Fetching example hooks/classes
import React, { useState, useEffect, Component } from 'react';
import { UserAccount } from './typings';
// Example using hooks
export default function App(): React.ReactElement {
const [users, setUsers] = useState<UserAccount[]>([]);
useEffect(() => {
mockApi.fetchUsers()
.then(setUsers);
}, []);
return (
<div>
{users.map(({ name }) => (
<span>User: {name}</span>
))}
</div>
);
}
// Example using componentDidMount
interface State {
users: UserAccount[];
}
class App2 extends Component<null, State> {
state = {
users: []
};
componentDidMount() {
mockApi.fetchUsers()
.then(users => {
this.setState({ users });
});
}
render() {
return (
<div>
{this.state.users.map(({ name }) => (
<span>User: {name}</span>
))}
</div>
);
}
}
const mockApi = {
fetchUsers(): Promise<UserAccount[]> {
return new Promise((resolve) => {
setTimeout(() => resolve(data), 500);
});
}
};
const data: UserAccount[] = [
{
name: "David Davidson",
bank: "Scottish Bank",
accountType: "current",
balance: 500
},
{
name: "Robert Paulson",
bank: "London Bank",
accountType: "savings",
balance: 10000
},
{
name: "David Davidson",
bank: "London Bank",
accountType: "savings",
balance: 5000
},
{
name: "Regina George",
bank: "Yorkshire Finance",
accountType: "current",
balance: 999
},
{
name: "Regina George",
bank: "Yorkshire Finance",
accountType: "savings",
balance: 1001
},
{
name: "Philip Johnson",
bank: "Scottish Bank",
accountType: "current",
balance: 869
},
{
name: "Claire Philips",
bank: "London Bank",
accountType: "current",
balance: 1234
},
{
name: "Megan Reid",
bank: "Scottish Bank",
accountType: "current",
balance: -200
},
{
name: "John Edwards",
bank: "Scottish Bank",
accountType: "current",
balance: -500
},
{
name: "Michael Komorowski",
bank: "Yorkshire Finance",
accountType: "current",
balance: 999
},
{
name: "Michelle Johnson",
bank: "Yorkshire Finance",
accountType: "current",
balance: 800
}
];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment