skip to Main Content

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 => {
  ...
 }
}

2

Answers


  1. Chosen as BEST ANSWER

    getData() is a promise inside a function. In that method, I returned the promise and did like this to solve this issue,

    const onRefresh = useCallback(async () => {
        setRefreshing(true);
        getData().then(() => {
         setRefreshing(false);
        });
     }, []);
    

  2. 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);
      }, []);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search