How do I get TouchableOpacity to call functions in a specifid order?

177 Views Asked by At

I am trying to set the state of a component prior to making the API call. The problem is the API call being called first. Here is what I have.

onPress={() => {
  setMeal('dinner');
  addToLogButtonPressed();
}}

When I press the button addToLogButtonPressed(); calls first which causes an error.

How to I call setMeal before addToLogButtonPressed?

2

There are 2 best solutions below

1
On

I think you can use useEffect to do that

const [meal, setMeal] = useState('')

useEffect(() => {
  addToLogButtonPressed();
}, [meal])

onPress={() => {
  setMeal('dinner');
}}
0
On

I also face this problem for my previous project simply just pass meal value to your addToLogButtonPressed() and access it inside the function. If you are not using "dinner" value anywhere else you can skip setting state it will save you one Re-render.

onPress={() => {
 setMeal('dinner');
 addToLogButtonPressed('dinner'); // like this
}}