lost9123193
lost9123193

Reputation: 11040

Access Redux State Object Property in Function

I have an inline function in my react component set up like this:

render() {
    const { post } = this.props;

    return (
        <div>
            {function(){
                if ({post}) {
                    return <h1>Post name exists {post.name}</h1>
                } else {
                    return <h1> Post name does not exist</h1>
                }
            }.call(this)}
     .....

and I have redux state set up like this:

function mapStateToProps(state) {
    return { 
        post:state.post.single,
    };
}

The above code works, but what I really want to check is if post.name is null or not, in which case I render different things on the page. However, I keep getting an error when I do this:

if({post.name})

Upvotes: 0

Views: 1072

Answers (3)

lost9123193
lost9123193

Reputation: 11040

I managed to get it WORKING by calling the function instead of doing an inline call:

renderCheck(){
    if(this.props.post.name){
      return (
        <div>
          ....
        </div>
      )
    }
 }

In the render I called it like this:

 {this.renderCheck()}

I'm still unsure why const { post : { name } } = this.props; didn't work but I will be using this for now.

Upvotes: 0

Michael Rasoahaingo
Michael Rasoahaingo

Reputation: 1089

Hi use a renderCheck function is a good approach if you have to do some test. But you have to do a double check props.post and props.post.name :( To avoid this "nested" checks I'm using ImmutableJS, then in my connect I would have

name: state.getIn(['post'], ['name'])

That will return undefined either post or name is undefined or null :)

Upvotes: 1

Avraam Mavridis
Avraam Mavridis

Reputation: 8920

You are trying to extract value of object inside of an if, you can't do that, e.g.:

function something(post){
  if({ post.name })
  {

  }

}

or even

function something(post){
  if({ post})
  {

  }

}

Is not valid js, you can check it in babel repl

What you can do is

const { post : { name } } = this.props;

And then check with if(name)

Upvotes: 2

Related Questions