Home > Mobile >  React native fetch api value not updating after change with useState()
React native fetch api value not updating after change with useState()

Time:12-31

as I mentioned in the title, when I select a new value in my Picker, the console show that everything is ok but my fetch don't want to update it with the new selectedValue.

If I pass manually an argument into the useState, the fetch update it but I don't know how to force it to update automatically. Here the code :

export default function Bien() {

  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);

  // problem here
  const [selectedValue, setSelectedValue] = useState('tous');
  const fetchValue = 'https://www.api.lereseaufoncier.fr/stock?category='   selectedValue
  // the console.log works and show the new selectedValue
  console.log(fetchValue)

  //but here, the query don't refresh
  //if I pass 'maisons' or 'appartements' in the new state manually, it works
  useEffect(() => {
      fetch(fetchValue)
        .then((response) => response.json())
        .then((json) => setData(json ? json.table : []))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));
    }, []);
  
  
  const postLayoutComponent = data.map(table => <AEPostLayout key={table.ID} table={table}/> )
    return (
  <SafeAreaView>
    <View style={{justifyContent: 'center', alignItems: 'center', width:'100%'}}>
    <Spacer taille={30} />
    <Picker
        selectedValue={selectedValue}
        style={{ height: 50, width: 195 }}
        onValueChange={(itemValue, itemIndex) => setSelectedValue(itemValue)}
      >
        <Picker.Item label="Tous Nos Biens" value="tous" />
        <Picker.Item label="Nos Maisons" value="maisons" />
        <Picker.Item label="Nos Terrains à bâtir" value="terrains à bâtir" />
        <Picker.Item label="Nos Appartements" value="appartements" />
      </Picker>
    <Spacer taille={10} />
    </View>
      <ScrollView>
        {postLayoutComponent}
      </ScrollView>
  </SafeAreaView>
    );
  }

I hope someone can help me. Thank you

CodePudding user response:

Try the following:

useEffect(() => {
      const fetchValue = 'https://www.api.lereseaufoncier.fr/stock?category='   selectedValue

      fetch(fetchValue)
        .then((response) => response.json())
        .then((json) => setData(json ? json.table : []))
        .catch((error) => console.error(error))
        .finally(() => setLoading(false));
    }, [selectedValue]);

That way, adding the dependency to useEffect tells the hook that every time selectedValue has changed, the component should re-render and re-fetch the data.

CodePudding user response:

Thank you all it works. And also thank you for the link to the doc.

  • Related