My idea is that when someone put a text in my TextInput and clicks submit then botToc() will save the data from that API search in result and show the result in a FlatList.
But I have a problem saving data with hooks. The thing is that my setResult is not working properly because it does not save well the data from the API query. botToc() is supposed to fetch data from an API and its doing that fine but then I loop through the fetched data and I save what I want in result using setResult.
The thing is that when I click the button that uses botToc2() ( after clicking the button that uses botToc() ) my console.log(result) shows only the data of the last element and if I use again botToc() and I click one more time botToc2() I get that last element duplicated in the result array.
How can I fix this?
export default function TestScreen () {
const [querypar, setQuerypar] = useState('');
const [apipar, setApipar] = useState('https://API/search?q=');
const [result, setResult] = useState([]);
const ItemView = ({item}) => {
return (
<View>
<Text>
{item[0]+ ' ' + item[1]}
</Text>
</View>
);
};
function botToc() {
let query = apipar+querypar; //'https://API/search?q='+'TextInputText'
let cargador = [];
fetch(query) //'https://API/search?q=TextInputText'
.then( res => res.json() )
.then( res => {
// (res.results) = [{price:x,title:x},{price:x,title:x},{price:x,title:x}] structure of (res.results)
(res.results).forEach( (element) => {
cargador.push(element.title);
cargador.push(element.price); //cargador=[x,x]
setResult([...result, ...cargador]); //result=[[x,x],[x,x]...]
cargador.length = 0; //cargador=[]
});
})
};
function botToc2() {
console.log(result); //my console should return [[x,x],[x,x],[x,x],[x,x],[x,x],[x,x],...]
};
return (
<View View style={styles.container}>
<TextInput placeholder="write here" onChangeText={(val) => setQuerypar(val)} />
<View>
<Button onPress={botToc} title="Submit"/>
<Button onPress={botToc2} title="Submit"/>
<FlatList
data={result}
renderItem={ItemView}
keyExtractor={(item, index) => index.toString()}
/>
</View>
</View>
);
};