I try to fetch data from Firebase with Axios and Redux to handle the state, Everything Is fine and I could console.log the data too, but FlatList doesn't show any data, Here is my Code:
Here is the Action of Redux.
import axios from "axios";
import { GET_PRODUCTS } from "./types";
export const fetchData = () => {
return (dispatch) => {
return axios
.get("https://learn-efc13-default-rtdb.firebaseio.com/products.json")
.then((response) => {
return response.data;
})
.then((data) => {
dispatch({
type: GET_PRODUCTS,
payload: data,
});
console.log(data);
})
.catch((error) => {
throw error;
});
};
};
Here is the reducer
import { GET_PRODUCTS } from "./types";
const initState = {
availableProducts: [],
};
const reducer = (state = initState, action) => {
switch (action.type) {
case GET_PRODUCTS:
return {
availableProducts: action.availableProducts,
};
default:
return state;
}
};
export default reducer;
And finally, the Screen, That contains the FlatList
import React, { useEffect } from "react";
import { View, Text, FlatList } from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { fetchData } from "./store/action";
function ScreenMain() {
useEffect(() => {
dispatch(fetchData());
}, [dispatch]);
const data = useSelector((state) => state.availableProducts);
const dispatch = useDispatch();
return (
<View style={styles.con}>
<FlatList
data={data}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<Text>
{item.name}
{item.age}
</Text>
)}
/>
</View>
);
}
export default ScreenMain;
I Added the useEffect hook to console.log data
can you wrap the <FlatList />
like this:
{data &&
<FlatList
data={data}
keyExtractor={(item) => item.id.toString()}
renderItem={({ item }) => (
<Text>
{item.name}
{item.age}
</Text>
)}
/>}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.