Last active
November 9, 2021 15:44
-
-
Save Jahans3/020a54c96b0dbc4f2a92c4dffb936e0e to your computer and use it in GitHub Desktop.
Fetching example hooks/classes
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, { 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