ignos555
ignos555

Reputation: 71

getting data from api before page renders react-native hooks

thats it i need to get the values from the api before this one loads the slider this is how i call the api

useEffect(() => { 
  async function BCcontroller() {
    const vCreationUser = 6;
    const vSolicitudeId = 8;
    const { data } = await ForceApi.post(`/ConsultBCController.php`, {vSolicitudeId, vCreationUser});
    const values = data.terms;
    setpterms(data.terms);
    //console.log(values);
    const [termA, termB, termC, termD] = values.split(',');
    setvA(Number(termA));
    setvB(Number(termB));
    setvC(Number(termC));
    setvD(Number(termD));
    // console.log(values);
  }
  BCcontroller();
}, );

this is the slider code

<View style={{ alignItems: "stretch", justifyContent: "center" }}>
  <Slider
    maximumValue={D > 0 ? 4 : 3}
    minimumValue={1}
    step={1}
    value={valuesFromApi.indexOf(Value)}
    onValueChange={index => setValue(valuesFromApi[index])}
  />
  <View style={styles.plazos}>
    <Text style={styles.plazo1}>{A} meses</Text>
    <Text style={styles.plazo2}>{B} meses</Text>
    <Text style={styles.plazo3}>{C} meses</Text>
    {D > 0 ? <Text style={styles.plazo3}>{D} meses</Text> : null}
  </View>
  <Text style={styles.slideText}>Su credito por: ${A}MXN</Text>
  <Text style={styles.slideText}>Usted recibe: ${A}MXN</Text>
  <Text style={styles.slideText}>A un plazo de: {sliderValue2} meses</Text>

  <Text style={styles.PaymentText}>Su pago: ${A}.00 MXN</Text>
</View>

i thougt it was this way but the screen loads with a lot of undefineds and then it get the values of the api, so i want to have the values first and then render te components thanks for your help

Upvotes: 0

Views: 700

Answers (1)

Christiaan Westerbeek
Christiaan Westerbeek

Reputation: 11137

You probably want your component to return null when there is no data yet. Only when the data is there, you can return the view+Slider.

Something like this:

const MyComponent = () => {
  const [data, setDate] = useState();

  useEffect(() => {
    // ...
    const { data } = await ForceApi.post(`/ConsultBCController.php`, {vSolicitudeId, vCreationUser});

    setData(data)
    // ...

  }, [])

  if (!data) return null;

  return (
    <View style={{ alignItems: "stretch", justifyContent: "center" }}>
      // ...
    </View>
  ) 
}

When data is there, you call setData which will cause a rerender returning the View+Slider.

Of course the code above is incomplete and untested. It's intended to convey my intention. If it doesn't quite make sense, leave a comment and I'll try to enhance.

Upvotes: 1

Related Questions