Dave_888
Dave_888

Reputation: 433

REACT fetch before rendering

I try to map the fetched data but I always get an error in my mapping because the data hasn't fetched before I use the map function. I'm able to get a get a specific element in from my fetched data using a click event.

enter image description here

parent class where I fetch my datas, I need the beer data for my mapping.

class App extends Component{


    constructor(props){
        super(props);
        this.props.fetchUser();
        this.props.fetchBeers();
    }

class where I try to map my beers:

class BeersLanding extends Component{



 getBeers = () => {
     let beers= this.props.beers;
     console.log(beers);
     console.log(beers[0]);
     console.log(beers[1]);

 }

 constructor(props){
     super(props);

 }

render(){

    const {loading} =this.props;


   console.log(this.props.beers)

    return(


        <div style={{textAlign:'center'}}>

           ...

                <input type="text" placeholder="Search.." name="search"></input>
                <button type="submit" onClick={() =>this.getBeers()} >Submit</button>

            <div className={'beersContainer'}>

                 {this.props.beers.map((beer,index) =>(
                    <div className={'card'}>
                    hello
                    </div>
                ))}  

            </div>
        </div>
    );
}

}

Action method:

export const fetchBeers = () => async dispatch => {

    const res = await axios.get('/api/beers');
    dispatch({type:FETCH_BEERS, payload:res.data});
};

reducer:

export default function(state=null, action){

    // console.log(action);
    switch(action.type){
    case FETCH_BEERS:
        return action.payload; 

    default:
        return state;
    }
}

Upvotes: 0

Views: 1878

Answers (2)

leogoesger
leogoesger

Reputation: 3830

I would recommend using react life cycle hooks for this type of issues.

componentDidMount() {
    this.props.YOURACTIONS()
}

So this will happen when component is loaded.

Upvotes: 1

Mohamed Binothman
Mohamed Binothman

Reputation: 378

There are tow options to solve this issue, first option and I recommended to use this, by using defaultProps and set default value of bees as array. the second option by add condition before map your data

{this.props.beers && this.props.beers.map((beer,index) =>(
                    <div className={'card'}>
                    hello
                    </div>
                ))}  

Upvotes: 1

Related Questions