0

When the function is called it should display the price State immediately

const  db_price= (objekt) => {
    Axios.post('http://localhost:3002/custom_price',{
        sku: objekt.sku, 
      }).then(res =>{        
        setPrice(res.data[0].item_price+" €");
      })
  };
  • 1
    What do you mean "immediately"? If nothing else, the _request_ will take noticeable time. – jonrsharpe Apr 25 '22 at 16:16
  • 1
    You can change the state first and then send the db request (optimistic UI updates). – emre-ozgun Apr 25 '22 at 16:16
  • Do you actually _know_ the new price up-front? It seems to be in the body of the response. – jonrsharpe Apr 25 '22 at 16:20
  • Another option to give the impression of instant loading would be to prefetch prices that are likely to be displayed (e.g. based on current location). – DBS Apr 25 '22 at 16:20
  • I have a map function when I click on an object of the list, this function is executed. Ideally, it should show directly the price of the selected object, but it always shows only the price of the previous object, because the state is not updated immediately. – Niklas Opp Apr 25 '22 at 16:24
  • @NiklasOpp — Asynchronicity is a fundamental of JS programming. You need to learn how to use it, not try to avoid it. `Axios.post` is asynchronous, and `setState` is asynchronous. Use `useEffect` to run code in response to state changes (or forget about state entirely and return a promise with the resolved value and use `Promise.all` on the result of your `map`. – Quentin Apr 25 '22 at 16:30

0 Answers0