Reputation: 425
I am able to fetch data from the Firebase API. I am able to set the state into the data received (I can see in Console). But when I am unable to render a Component (passing props as fetched data). Here' my code:
class NewMeals extends Component {
constructor(props){
super(props);
this.state= {
data:''
}
}
async componentDidMount(){
try{
const res = await fetch('https://frego-cb5b5.firebaseio.com/recipes.json?auth=api_key');
if(!res.ok){
throw Error(res.statusText);
}
const json = await res.json();
this.setState({data:json});
}catch(err){
console.log(err);
}
}
renderItems=()=>{
const items = this.state.data;
const arr = Object.values(items);
arr.forEach(i=>{
return <HomeMeals name={i.title} time={i.time} serve={i.serve}/>
})
}
render(){
const {mainView, CardSection, heading, } = styles;
return(
<View style={mainView}>
<Text style={heading}>New Meals This Week</Text>
<ScrollView contentContainerStyle ={CardSection} horizontal={true} showsHorizontalScrollIndicator={false}>
{this.renderItems()}
</ScrollView>
</ View>
);
}
}
I expect the HomeMeals Components will render one by one with particular names from fetched data upon calling renderItems() function. But I am getting nothing.
Any suggestions?
Upvotes: 1
Views: 394
Reputation: 755
A couple of points here.
const items = this.state.data;
const arr = Object.values(items);
console.log("items and arr", items, arr, this.state);
What values do you see from the logs above? That should give you a hint.
renderItems=()=>{
arr.forEach(i=>{
return <HomeMeals name={i.title} time={i.time} serve={i.serve}/>
})
...
What you would want is return elements (array of elements) from renderItems function like this:
renderItems=()=>{
return arr.map(i=>{
return <HomeMeals name={i.title} time={i.time} serve={i.serve}/>
})
...
Two things you will notice: (1) I added return keyword to return whatever arr.map returns. And (2) the use of arr.map vs arr.forEach. Try to figure out the reason of this on your own; why arr.map works and arr.forEach doesn't
Upvotes: 3