0

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;
    }
}
2
  • You get the error about select tag Commented May 23, 2018 at 18:20
  • 3
    don't trigger fetch in constructor, use componentDidMount. Also, you need to keep state whether you are loading or not. Then it's a question of simple checking that boolean before rendering "beers". Commented May 23, 2018 at 18:22

2 Answers 2

1

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>
                ))}  
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.