1

Hi I have a weird issue with state.

I am using the picker react native module

<Picker
              selectedValue={partnership}
              onValueChange={(itemValue, itemIndex) => {
                partnerHandler(itemValue);
              }}>
              <Picker.Item label="Partner" value="Partner" />
              <Picker.Item label="1K Partner" value="1KPartner" />
              <Picker.Item label="Business Partner" value="BusinessPartner" />
              <Picker.Item label="Ik ben al partner" value="AlPartner" />
              <Picker.Item label="Gratis Account" value="GratisAccount" />
          </Picker>

than when the value changes I run this function:

const partnerHandler = (itemValue) => {
    console.log(itemValue);
    setPartnership(itemValue);
  }

so in the function I log the "itemValue" and that value I set to a state "partnership"

now this...

useEffect(() => {
    console.log(partnership);
    if (partnership === "BusinessPartner"){
      setMinValuePartnershipPrice(250);
    } else if (partnership === "1KPartner"){
      setMinValuePartnershipPrice(83);
    } else if (partnership === "Partner"){
      setMinValuePartnershipPrice(25);
    }
    console.log(minValuePartnershipPrice)
  }, [partnership])

so I made a "useEffect" that runs when I render the page and when the state 'partnership' changes.

Now, when I log 'partnership' it gives me the result I want, but then with my if else statement it is not updating. When I pick "Business Partner" the "minValuePartnershipPrice" is still 25 and then when I pick "1KPartner" the "minValuePartnershipPrice" is 250. So the whole time it picks the number which I selected before. now when I press save in visual studio code it jumps to the correct data...

What am I doing wrong? The function only runs when the state is updated. when i log the data it gives me the correct partnership but then when i push the data in the if else it doesn't give me the result I want.

Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35

1 Answers1

1

You can't see minValuePartnershipPrice right after setting it as setState is async. Try adding another useEffect:

useEffect(() => {
     console.log(minValuePartnershipPrice)
}, [minValuePartnershipPrice]
Sinan Yaman
  • 5,714
  • 2
  • 15
  • 35