Przemek eS
Przemek eS

Reputation: 1304

React/Redux firing action->render before update a store

A have a simply react/redux app. I Fetch data from API async but component not waiting for data and firing render.

class RestaurantList extends React.Component {
componentWillMount() {
    this.props.getRestaurantList();
}

render() {
    console.log("render");
    let {translation} = store.getState().app;
    //------------I NEED DATA ON THIS LET (restaurantList)
    let {restaurantList} = this.props.restaurants;


    return (
        <div>
            <TableContainer data={restaurantList}/>
        </div>

    )


   }
}
const mapStateToProps = (state) => {
return {
    restaurants: state.restaurants
};
};

const mapDispatchToProps = (dispatch) => {
    return {
        getRestaurantList() {
            dispatch(ACTIONS.getRestaurantList());
        },
    };
};

export default connect(mapStateToProps, mapDispatchToProps)(RestaurantList);

On my action i fetching data using axios :

export function getRestaurantList() {
console.log("action");
return dispatch => {
    axios({
        method: "GET",
        url: URLS.BASE_URL + URLS.URL_RESTAURANT_LIST
    }).then((response) => {
        console.log(response);
        dispatch({
            type: CONST.GET_RESTAURANT_LIST,
            payload: response.data
        })
    })
}
}

And my component fired method ComponenWillMount after that render () and next store which update store and set good data to my variable. Maybe u give me advice how to do that to have on my render my fetching data because now on my table I transfer undefined on start. Maybe you give me an example to using another framework like redux-saga or other.

Upvotes: 0

Views: 260

Answers (1)

Steve Holgado
Steve Holgado

Reputation: 12071

You could try conditionally rendering your TableContainer component so the table will only be rendered once there is data available:

renderTable() {
  let { restaurantList } = this.props.restaurants

  if (restaurantList) {
    return <TableContainer data={ restaurantList } />
  } else {
    return <div></div>
  }
}

render() {
  return (
    <div>
      { this.renderTable() }
    </div>
  )
}

Upvotes: 2

Related Questions