Here I have a promise inside refresh control method,
const Component = () => {
const [refreshing, setRefreshing] = useState(false);
const onRefresh = useCallback(() => {
setRefreshing(true);
getData();
setRefreshing(false);
}, []);
return (
<ScrollView
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}>...</ScrollView>
);
}
How to wait for the getData()
function and after that set refresh to false? Problem is it isn't waiting for the getData()
function to finish. (getData() is a promise)
the getData() function,
const getData = () => {
axios.get(`https://somedomain.com/fetch/user/1`).then(res => {
...
}
}
CodePudding user response:
const Component = () => {
const [refreshing, setRefreshing] = useState(false);
const getData = () => {
axios.get(`https://somedomain.com/fetch/user/1`).then(res => {
...
setRefreshing(false);
}
}
const onRefresh = useCallback(() => {
setRefreshing(true);
getData();
}, []);
return (
<ScrollView
refreshControl={
<RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
}>...</ScrollView>
);
}
Alternative:
const getData = async () => {
const response = await axios.get(`https://somedomain.com/fetch/user/1`);
//Handle your response here
}
const onRefresh = useCallback(async () => {
setRefreshing(true);
await getData();
setRefreshing(false);
}, []);