ignos555
ignos555

Reputation: 71

How to assign values in react native

I get 4 values from an api [10, 20, 22, 26]. These values are assigned to [A, B, C, D] and I have a slider that has these values [1, 2, 3 ,4].

What I need is when you select 1 in the slider, it gives you the value of A (which is 10 in this case). If you select 2 in the slider it should give you the value of B (which is 20), and so on.

Do you have any idea how can i do this?

This is my code:

const [sliderValue2, setsliderValue2] = useState();
const [A, setvA] = useState();
const [B, setvB] = useState();
const [C, setvC] = useState();
const [D, setvD] = useState();
const [pterms, setpterms] = useState([]);
const [value, setValue] = useState(setpterms[0]);

<View style={{alignItems: 'stretch', justifyContent: 'center' }}>
    <Slider 
        maximumValue={D > 0 ? 4: 3 }
        minimumValue={1}
        step={1}
        value={pterms.indexOf(value)}
        onValueChange={index => setValue(pterms[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>

edit this is my api call

  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);
        const [termA, termB, termC, termD] = values.split(',');
        setvA(Number(termA));
            setvB(Number(termB));
            setvC(Number(termC));
            setvD(Number(termD));
    }
    BCcontroller();
}, []);

Upvotes: 2

Views: 123

Answers (1)

CampbellMG
CampbellMG

Reputation: 2220

You could store the value of your slider and use it as an index for the array from your API, something like this (working example):

export default function App() {
  const valuesFromApi = [10, 20, 22, 26];
  const [value, setValue] = useState(valuesFromApi[0]);

  return (
    <View style={styles.container}>
      <Text style={styles.paragraph}>{value}</Text>
      <Slider
        minimumValue={0}
        maximumValue={3}
        step={1}
        value={valuesFromApi.indexOf(value)}
        onValueChange={index => setValue(valuesFromApi[index])}
      />
    </View>
  );
}

Upvotes: 1

Related Questions