user4396386
user4396386

Reputation: 433

How to declare variable inside react function?

I'm having some difficulty setting variables inside my handleSubmit function. this.props.posts is an array of objects coming from redux. I simply want to grab a single post object that matches with the id of the prop I passed in. I think my confusion lies in not quite understanding what I'm actually supposed to be returning here. Any clarification would be appreciated. Thanks!

handleSubmit = (e) => {
e.preventDefault()
const  post  = 
  this.props.posts.map((el, i) => {
    if (el.id === this.props.id) {
      return el
    }
  })
console.log(post)
this.props.dispatch(updatePost(this.state.post))
this.props.closeForm()
}

Upvotes: 0

Views: 508

Answers (1)

tlm
tlm

Reputation: 1022

Array.prototype.map isn't what you're looking for. You should use the Array.prototype.find() method to locate the object by id.

const  post  = this.props.posts.find(el => el.id === this.props.id)

or something like that.

Upvotes: 1

Related Questions