1const MyFunctionnalComponent: React.FC = props => {
2 useEffect(() => {
3 // Using an IIFE
4 (async function anyNameFunction() {
5 await loadContent();
6 })();
7 }, []);
8
9 return <div></div>;
10};
1const getUsers = async () => {
2 const users = await axios.get('https://randomuser.me/api/?page=1&results=10&nat=us');
3 setUsers(users.data.results);
4};
5
6useEffect(() => {
7 getUsers();
8}, []);
1useEffect(() => {
2 (async function anyNameFunction() {await loadContent();})();
3}, []);
1function myApp() {
2 const [data, setdata] = useState()
3
4 useEffect(() => {
5 async function fetchMyAPI() {
6 const response = await fetch('api/data')
7 response = await response.json()
8 setdata(response)
9 }
10
11 fetchMyAPI()
12 }, [])
13}
1function Example() {
2 const [data, dataSet] = useState<any>(null)
3
4 useEffect(() => {
5 async function fetchMyAPI() {
6 let response = await fetch('api/data')
7 response = await response.json()
8 dataSet(response)
9 }
10
11 fetchMyAPI()
12 }, [])
13
14 return <div>{JSON.stringify(data)}</div>
15}
1 function OutsideUsageExample() {
2 const [data, dataSet] = useState<any>(null)
3
4 const fetchMyAPI = useCallback(async () => {
5 let response = await fetch('api/data')
6 response = await response.json()
7 dataSet(response)
8 }, [])
9
10 useEffect(() => {
11 fetchMyAPI()
12 }, [fetchMyAPI])
13
14 return (
15 <div>
16 <div>data: {JSON.stringify(data)}</div>
17 <div>
18 <button onClick={fetchMyAPI}>manual fetch</button>
19 </div>
20 </div>
21 )
22}
23