1
votes

i am using react and redux for my application. My problem is i receive 2 time my props the first is undefined and the second is ok. So i cannot use the props.

import ...

class Home extends Component {
  
  //some code logic 
  
  render(){
 console.log(this.props.header);
 
 const header = this.props.header;
  
    return (
      <Welcome title={header.title} />
    )
  }

}


const mapStateToProps = (state) => {
  return {
    header: _.find(state.header, { 'page': 'accueil' })
  }
}

export default connect(mapStateToProps)(Home);

console.log give me 2 answer : 1 / undefined 2 / Array of obj (that what i need)

Uncaught TypeError: Cannot read property title of undefined

enter image description here

1
Need a little more to go on here. When is state.header being set? After an API call? It might be as simple as adding if (!this.props.header) return null to the start of the render function, but that might only hide the issue and not fix the cause. - Michael Peyper
Yes i calling it from an API. So if i pass it to child it does not work but if i am doing a normal loop inside this component it work well. - Nicks
If that's the case, it is not unexpected that it is undefined the first time it renders (it hasn't got the data yet). returning null isn't doing a "loop" inside the component, it is saying there is noting to render, which there isn't in the case of the initial render. You could also return some kind of Loading component instead of null for a better user experience. - Michael Peyper

1 Answers

1
votes

The problem is quite simple. In your case when you define a reducer the initial state would be set to undefined which will be returned the first time and later after some processing the date will be returned. So you can do two things

First: set the initial state in reducer

var initialState = {
   id: '',
   page: '',
   title: '',
   metaTitle: '',
   subtitle: ''
}
const reducerState = (state = initialState, action) => {

  ......  //Do what you want here
   return state
}

Second: check if the header.title is defined in component

class Home extends Component {

  //some code logic 

  render(){
 console.log(this.props.header);

 const header = this.props.header;

    return (
      {header.title && <Welcome title={header.title} />}
    )
  }

}


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

export default connect(mapStateToProps)(Home);