Home > Mobile >  problem handling promise in useState React
problem handling promise in useState React

Time:08-24

After selecting two values ​​from a list, I must make a call to an api that returns a Json with the information

In this way I call the api that responds with the JSON

export default class ProductsService {
   
   async getProducts(channel, category){
       const aux = await axios.post('https://appshop.dapducasse.cl/ducasse-api/api/Qrs?channel=' encodeURIComponent(channel) '&category=' encodeURIComponent(category)).then(data =>data.data).catch(e => [])
      
       return aux
   } 
}

In this way I make the call from the react component

  const chanelService = new ChanelService();
   const categoryService = new CategoryService();
   const productsService = new ProductsService();

   

   useEffect(() => {
       chanelService.getChanels().then(data => setChanels(data))
       categoryService.getCategories().then(data => setCateries(data))
   }, []);

   const testChargue = async ( ) =>{
       console.log(selectedChannel)
       console.log(selectedCategory)
       const a = await productsService.getProducts(selectedChannel, selectedCategory).then(data => setProducts(data));
       console.log(products)

   }


When I press the button, the function should be executed where the call is made with the Channel and the selected product.

I don't get the json on the first click of the button, but on the second, I think this happens because the execution ends before setProducts defines the state of products.

CodePudding user response:

I assume products and setProducts refer to local state in your component?

In this case products in the last line will always be the "old" value inside your handler function, because setProducts will not update that variable. The variable will only changed when the component will been re-rendered, but not during the execution of your handler function. I think that's why you see the value when pressing the button twice. On the second click the component has been re-rendered, so the value also in your handler function has been updated.

More on "stale" state in the react docs: https://reactjs.org/docs/hooks-faq.html#why-am-i-seeing-stale-props-or-state-inside-my-function

  • Related