async callback in useEffect code example
Example 1: useeffect async await
const getUsers = async () => {
const users = await axios.get('https://randomuser.me/api/?page=1&results=10&nat=us');
setUsers(users.data.results);
};
useEffect(() => {
getUsers();
}, []);
Example 2: async useEffect
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>
)
}