xxxxxxxxxx
const [users, setUsers] = useState([]);
useffect(() => {
const getUsers = async () => {
let response = await fetch('/users');
let data = await response.json();
setUsers(data);
};
getUsers();
}, []);
xxxxxxxxxx
const MyFunctionnalComponent: React.FC = props => {
useEffect(() => {
// Using an IIFE
(async function anyNameFunction() {
await loadContent();
})();
}, []);
return <div></div>;
};
xxxxxxxxxx
useEffect(() => {
(async () => {
const products = await api.index()
setFilteredProducts(products)
setProducts(products)
})()
}, [])
xxxxxxxxxx
function myApp() {
const [data, setdata] = useState()
useEffect(() => {
async function fetchMyAPI() {
const response = await fetch('api/data')
response = await response.json()
setdata(response)
}
fetchMyAPI()
}, [])
}
xxxxxxxxxx
useEffect(() => {
async function fetchData() {
try {
const response = await fetch(
`https://www.reddit.com/r/${subreddit}.json`
);
const json = await response.json();
setPosts(json.data.children.map(it => it.data));
} catch (e) {
console.error(e);
}
};
fetchData();
}, []);
xxxxxxxxxx
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>
}
xxxxxxxxxx
useEffect(() => {
const getUsers = async () => {
const users = await fetchUsers();
setUsers(users);
};
getUsers(); // run it, run it
return () => {
// this now gets called when the component unmounts
};
}, []);
xxxxxxxxxx
const [books, setBooks] = useState([]);
useEffect(() => {
(async () => {
try {
// await async "fetchBooks()" function
const books = await fetchBooks();
setBooks(books);
} catch (err) {
console.log('Error occured when fetching books');
}
})();
}, []);
xxxxxxxxxx
const getUsers = async () => {
const users = await axios.get('https://randomuser.me/api/?page=1&results=10&nat=us');
setUsers(users.data.results);
};
useEffect(() => {
getUsers();
}, []);
xxxxxxxxxx
useEffect(() => {
(async function anyNameFunction() {await loadContent();})();
}, []);