Home > Software engineering >  How to use a state in a call to an API
How to use a state in a call to an API

Time:06-04

I try to insert a exemple API in my code React Native and I want to use a state in the link of my API but it doesn't work. The users input a CP in a TextInput and then it's saved in the state then I want to put that CP state in the link

Can you help me :

import React, {useState, useEffect} from 'react';
import { SafeAreaView, Text, View, StyleSheet, TextInput, TouchableOpacity, Picker } from 'react-native';
import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';


export default function Localisation({ navigation }) {

  const [CP, setCP]= React.useState('3');
  const [city, setCity]= React.useState('');
  const [ListVille, setList]= React.useState([]);

  useEffect( () => {
    getCities()
  }, []);

  const getCities = () => {
    fetch('https://reqres.in/api/users/CP/').then(function(response) {
      return response.json()
    }).then(function(response){
      setList(response.data)
      console.log(response.data)
      console.log(Array.isArray(response.data))
    })
  }

  return (
  <SafeAreaView style={styles.plus}>
    <Text> Saisissez votre code postal. </Text>
    <TextInput style={styles.input} value={CP} placeholder='Code postal' onChangeText={text => setCP(text)}  keyboardType='number-pad'/>
    <Text> Selectionner la commune de votre choix  </Text>
    <Picker selectedValue={city}
      onValueChange={(itemValue) => setCity(itemValue)} 
      placeholder={{label: 'Choisissez une ville', value: null, color: '#9EA0A4',}}>
      { Array.isArray(ListVille) ? ListVille.map((item, key)=>( <Picker.Item label={item.first_name} value={item.first_name} key={key} />) ) : ListVille===undefined ?  <Picker.Item label={''} value={'pas de ville'} /> : <Picker.Item label={ListVille.first_name} value={ListVille.first_name} /> }
    </Picker>
    
    <View style={{alignItems: "center",}}>
      <TouchableOpacity onPress={() => { navigation.navigate('Ma simulation', {ville: city} ) }} style={styles.button} >
        <Text> Valider </Text>
      </TouchableOpacity>
    </View>
  </SafeAreaView>
  );
}

const styles = StyleSheet.create({
  plus: {
    margin:10,
  },

  input: {
    backgroundColor:'white',
    borderWidth: 0.5,
    borderColor:'#C5C5CC',
    borderRadius: '10px',
    marginBottom:20,
    marginTop: 10,
    marginLeft:5,
    color: '#616161',
    width: '98%',
    height: 40,
    padding: 10,
  },

  button: {
    backgroundColor: '#92D050',
    boxSizing: 'border-box',
    borderRadius: '10px',
    alignItems: "center",
    padding: 10,
    color: '#616161',
    width: '70%',
    marginLeft:20,
    marginTop:20,
  },
}); 

const pickerSelectStyles = StyleSheet.create({
  inputIOS: {
    padding: 10,
    width:'98%',
    borderWidth: 0.5,
    borderColor: '#C5C5CC',
    borderRadius: 10,
    color: '#616161',
    alignItems: "center",
    marginTop: 10,
    marginLeft:5,
    paddingRight: 30, // to ensure the text is never behind the icon
  },
  inputAndroid: {
    fontSize: 16,
    paddingHorizontal: 10,
    paddingVertical: 8,
    borderWidth: 0.5,
    borderColor: 'purple',
    borderRadius: 8,
    color: 'black',
    paddingRight: 30, // to ensure the text is never behind the icon
  },
});

/* pour plus tard quand on pourra choisir la ville
  const [CP, setCP]= React.useState('');

  <Text> Saisissez votre code postal. </Text>
  <TextInput style={styles.input} value={CP} placeholder='Code postal' onChangeText={text => setCP(text)}  keyboardType='number-pad'/>

  <Text> Selectionner la commune de votre choix </Text>
  <TextInput style={styles.input} value={city} placeholder='Ville' onChangeText={text => setCity(text)}  />


  
*/
      

I tried :

When I put a number like :

CodePudding user response:

This is just a string:

'https://reqres.in/api/users/CP/'

It may contain the same characters as a variable name, but there's nothing indicating to JavaScript that this is anything other than a string.

You're looking for a template literal:

`https://reqres.in/api/users/${CP}/`

Or, at worst, looking to concatenate a variable into a string:

'https://reqres.in/api/users/'   CP   '/'
  • Related