I am fetching data with Axios according to search term that user typed. When I console.log the response; the data looks fine. I also assign the response to a state and console.log that state succesfully as well. But whenever I want to show the data on the FlatList component, list items appear, but the list items are empty. Also number of the list items is not equal with the data, which is another problem.
My code is below. I tried changing "extraData" property of FlatList into both search
and searchResults
, but it did not help.
By the way, when I remove the useEffect hook completely, and give a static state, it shows the static data as expected.
const [search, setSearch] = useState("");
const [searchResults, setSearchResults] = useState(null);
useEffect(() => {
axios
.get(
`http://BASE_URL/api/${props.categoryName}/${search}`
)
.then((response) => {
setSearchResults(response.data.result);
})
.catch((error) => {
console.log(error);
});
console.log(searchResults);
}, [search]);
.
.
.
<FlatList
extraData={search}
keyboardShouldPersistTaps={"always"}
style={styles.list}
data={searchResults}
renderItem={({ item }) => (
<Pressable
style={[styles.item, props.itemStyle]}
onPress={() => onSelect(item)}>
<Text style={[styles.itemText, props.itemTextStyle]}>
{item.Name}
</Text>
</Pressable>
)}
/>
Additionaly, this is the response I see on console when i type "god" into search bar:
[{"Id":2,"Name":"The Godfather","Year":1972},{"Id":4,"Name":"The Godfather Part II","Year":1974}]
I changed the
setSearchResults(response.data.result);
with
setSearchResults((prevResults) => JSON.parse(response.data.result));
and the problem solved!