TransWikia.com

How do I run one function after another one in React?

Stack Overflow Asked by D Park on January 3, 2022

In my code, I have loadData() and useFilter(). I tried to run loadData() first as productsData need to be set for useFilter() to process productsData. However, I tried .then() but it still gives me undefined when I console log useFilter() How do I fix this?

  const [productsData, setProductsData] = useState(null);

  const loadData = async () => {
    const { data } = await getAxios().get('/market/list').then(response => response.data)
    setProductsData(data)
  }

  const useFilter = () => {
    return productsData.map(data => (...))
    //filters productsData
  };

  useEffect(()=>{
    loadData().then(()=>useFilter());
  },[])

2 Answers

Hello just by making a function async doesn't make it return a promise in order to use .then on function calls you must make sure they return promises

So one implementation you could do is :

    const [productsData, setProductsData] = useState(null);

  const loadData = () => {
    return getAxios().get('/market/list').then(response => response.data)
  }

  const useFilter = () => {
    return productsData.map(data => (...))
    //filters productsData
  };

  useEffect(()=>{
    loadData().then((data)=>{
    setProductsData(data);
    useFilter();
    }
   );
  },[])

In the above implementation I return the promise that axios returns you can also return your own promise by creating a promise using new Promise() constructor

Do let me know if you face any issues

Answered by Yash.S.Narang on January 3, 2022

Changing state asynchronous. So using state immediately after changing that may not be updated one.

You can use useEffect to call your function after state changed.

You can do this:

const [productsData, setProductsData] = useState(null);

const useFilter = () => {
  return productsData.map(data => (...))
  //filters productsData
};

useEffect(()=>{
  const loadData = async () => {
    const { data } = await getAxios().get('/market/list').then(response => response.data)
    setProductsData(data)
  }
  loadData()
},[])

useEffect(()=>{
  useFilter();
},[productsData])

Answered by BeHappy on January 3, 2022

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP