const MyFunctionnalComponent: React.FC = props => {
useEffect(() => {
// Using an IIFE
(async function anyNameFunction() {
await loadContent();
})();
}, []);
return <div></div>;
};
useEffect(() => {
(async () => {
const products = await api.index()
setFilteredProducts(products)
setProducts(products)
})()
}, [])
const [users, setUsers] = useState([]);
useffect(() => {
const getUsers = async () => {
let response = await fetch('/users');
let data = await response.json();
setUsers(data);
};
getUsers();
}, []);
useEffect(() => {
const getUsers = async () => {
const users = await fetchUsers();
setUsers(users);
};
getUsers(); // run it, run it
return () => {
// this now gets called when the component unmounts
};
}, []);
function myApp() {
const [data, setdata] = useState()
useEffect(() => {
async function fetchMyAPI() {
const response = await fetch('api/data')
response = await response.json()
setdata(response)
}
fetchMyAPI()
}, [])
}
useEffect(() => {
(async function anyNameFunction() {await loadContent();})();
}, []);
function Example() {
const [data, dataSet] = useState<any>(null)
useEffect(() => {
async function fetchMyAPI() {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}
fetchMyAPI()
}, [])
return <div>{JSON.stringify(data)}</div>
}
function OutsideUsageExample() {
const [data, dataSet] = useState<any>(null)
const fetchMyAPI = useCallback(async () => {
let response = await fetch('api/data')
response = await response.json()
dataSet(response)
}, [])
useEffect(() => {
fetchMyAPI()
}, [fetchMyAPI])
return (
<div>
<div>data: {JSON.stringify(data)}</div>
<div>
<button onClick={fetchMyAPI}>manual fetch</button>
</div>
</div>
)
}