1

I get this string 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. i can do this when i mock the data const valuesFromApi = [ 10,20, 22]; but i cant do the same with the data from my api, i guess that is because its a string and not an array.

this is my code

    const Calculadora = ({navigation}) => {
  const [sliderValue, setsliderValue] = useState();
  const [sliderValue2, setsliderValue2] = useState(A);
  const [A, setvA] = useState();
  const [B, setvB] = useState();
  const [C, setvC] = useState();
  const [D, setvD] = useState();
  const [pterms, setpterms] = useState([]);
  const valuesFromApi = [ 10,20, 22];
  const [value, setValue] = useState(valuesFromApi[0]);

this is how i get the data from 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(setpterms);
            const [termA, termB, termC, termD] = values.split(',');
            setvA(Number(termA));
            setvB(Number(termB));
            setvC(Number(termC));
            setvD(Number(termD));
    }
    BCcontroller();
}, []);

and this is my slider

<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>

any helpr would be appreciated

7
  • 2
    If you're not able to adjust properly data format sent from your backend, you may do JSON.parse() to turn your string into an array. Commented Jan 16, 2020 at 16:21
  • already tried this const { data } = await ForceApi.post(/ConsultBCController.php, {vSolicitudeId, vCreationUser}); const values = data.terms; const obj =JSON.parse(values); and it throwme undefined Commented Jan 16, 2020 at 16:47
  • If you share your response sample, I can adjust my answer accordingly so you will get acceptable answer ;) Commented Jan 16, 2020 at 17:15
  • the Object.values() didnt work, it splited everything the console log was Array [ "[","2","4","," "3", "6", ",", "4", "8", "]", ] Commented Jan 16, 2020 at 17:20
  • It could've happened if your source object has properties with empty string ('') values. As being said, you may share response sample, so I'll give complete answer. Otherwise, there's a huge room to make all sorts of guesses. Commented Jan 16, 2020 at 17:24

3 Answers 3

1

It appears to me that you're attempting to use the data before it arrives, would you use something like:

useEffect(() => { 
       const    vCreationUser = 6,
                vSolicitudeId = 8
       ForceApi.post(`/ConsultBCController.php`, {vSolicitudeId, vCreationUser}).then(data => {
            const   values = data.terms,
                    [termA, termB, termC, termD] = values
            setpterms(values)
            setvA(Number(termA))
            setvB(Number(termB))
            setvC(Number(termC))
            setvD(Number(termD))
       })
    }, [])

You may combine that with JSON.parse() if your API response is not structured properly:

const   values = JSON.parse(data.terms),
Sign up to request clarification or add additional context in comments.

4 Comments

this throws me 2 errors 1 says that TypeError: undefined is not an object (evaluating 'pterms[0]'). this is should be where i declare const [value, setValue] = useState(pterms[0]);
the second one says [Unhandled promise rejection: TypeError: undefined is not an object (evaluating 'values.split')]
I've cleared a clutter a bit, unfortunatelly, without your environment I can't troubleshoot more. However, you need to make sure your response structure matches to what is extracted with above function.
[Unhandled promise rejection: SyntaxError: JSON Parse error: Unexpected identifier "undefined"]
1

tries to do this but this gives me undefined since it prints the array like this [24,28,32,]

const JSONString = values;
   object = JSON.parse(JSONString);
   array = Object.keys(object).map(function(k) {
     return object[k];
   });

2 Comments

There's a shorter way to extract the value of each object property into array: Object.values()
i will try that because what i did helped but it gives me undefined on the last number
0

Here is a magic code to convert from string to array

'[10, 20, 22, 26]'
  .replace(/^\[/gi, '')
  .replace(/\]$/gi, '')
  .split(',')
  .map(v => v.trim())
  .filter(v => v !== "");

That would be an array of Strings. If you want an array of Numbers,

'[10, 20, 22, 26]'
  .replace(/^\[/gi, '')
  .replace(/\]$/gi, '')
  .split(',')
  .map(v => v.trim())
  .filter(v => v !== "")
  .map(v => Number(v))
  .filter(v => !isNaN(v));

3 Comments

sorry i dont get it, how do i implement that on my code, or how can i acces to the value of that?
Do you really need to re-invent the wheel?
@YevgenGorbunkov You are right. I didn't pay attention that initial string was a valid JSON.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.