Saumay Paul
Saumay Paul

Reputation: 425

Unable to render react-native Component after fetching data from firebase

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

Answers (1)

Tyro Hunter
Tyro Hunter

Reputation: 755

A couple of points here.

  1. Do more debugging (logs).
    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.

  1. This one below (renderItems) doesn't work, as it doesn't return elements (or anything) to render (as you were trying to):
    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

Related Questions