0

I used redux-thunk middleware and I'm receiving the values from props only after the render is executed. How can i get the values of 'Contents' to be set in props before render is called??

UNSAFE_componentWillMount() {
    this.getAllArticle();
}

getAllArticle = () => {
    this.props.onGetAllArticle(); `
}

render() {

 {this.props.contents ? this.props.contents.map((obj, index) => (
                        <tr key={index}>
                            <td> {obj.id} </td>
                            <td> {obj.title}</td>
                            <td> {obj.context}</td>
                        </tr> 
                    )) : 'No Data'}}

function mapStateToProps(state) {
 return {
   contents: state.all
 }
}

function mapDispatchToProps(dispatch) {
 return { 
   onGetAllArticle: () =>dispatch(actionCreator.onGetAllArticle())
  }
 }

export default connect(mapStateToProps, mapDispatchToProps)(All);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400

1 Answers1

0

Since you trigger a dispatch call in UNSAFE_componentWillMount(which I do not recommend as the name suggests it is unsafe and will be deprecated) the response that you receive will only be available after the initial render.

The solution is to show a loading state to the USER while the data is being fetched as you won't have the data on initial render. To do that have a loading state in your reducer which is initially set to true

render() {

   {this.props.contents ? this.props.contents.map((obj, index) => (
                        <tr key={index}>
                            <td> {obj.id} </td>
                            <td> {obj.title}</td>
                            <td> {obj.context}</td>
                        </tr> 
                    )) : this.props.isLoading? 'Loading...': 'No Data'
   }
}

function mapStateToProps(state) {
 return {
   contents: state.all,
   isLoading: state.isLoading
 }
}

function mapDispatchToProps(dispatch) {
 return { 
   onGetAllArticle: () =>dispatch(actionCreator.onGetAllArticle())
  }
 }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400