Reputation: 337
I am trying to fetch data from API on my localhost server using "Axios" in React Native but data in not fetching from API and nothing displaying.If you asking is the http request works in Server side yeah Thats working. Any comment and idea would be very much appreciated :)
http.common :
export default axios.create({
baseURL: "http://localhost:19002/api",
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,PATCH,DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
}
});
Card.js :
import dataAPI from '../http/http.common'
function Card() {
const [items, setItems] = useState([]);
useEffect(() => {
getDataFromAPI()
}, [])
function getDataFromAPI() {
dataAPI.get('/latest')
.then(async function (response) {
setItems(response.data);
})
.catch(function (error) {
console.log(error)
})
}
if (!items) {
return null
}
return (
<FlatGrid
itemDimension={130}
data={items}
style={styles.gridView}
spacing={10}
keyExtractor={(item, index) => 'key' + index}
renderItem={({ item }) => (
<TextCard item= {item} />
)}
/>
);
}
TextCard.js
const TextCard = ({item }) => {
console.log(item)
return (
<>
<View style={[styles.itemContainer, { backgroundColor: '#fff' }]}>
<Image style={styles.itemImg} source={require('../assets/temperature.png')} />
<Text style={styles.itemName}>Température</Text>
<Text style={styles.itemCode}>{item.Temperature} </Text>
</View>
</>
)
}
Upvotes: 0
Views: 751
Reputation: 282
Try passing extraData={{length: items.length}}
as a prop to the FlatList
And to make sure that the state is updated, add the following hook to the Card
component
useEffect(() => {
console.log(`There are ${items.length} items in the state right now`)
}, [items.length])
Let me know if its resolved, if not I'll have to replicate the issue and see where it stems from
Upvotes: 1