guillaumek guillaumek - 1 month ago 17
Javascript Question

Meteor/React, redirect route after changeState

I have a problem redirecting my routes with react router after a state change.

In fact, my route is working when I'm using a click event who change the state (currentListId), but it's not working when I delete an element by Id (listId), so after a setState( listSelected: "") ...
My routes still display the /idlistselected instead redirect to /.

Here is some code:

Page code:

constructor(props) {
super(props);
this.state = { listSelected: "" };
this.selectList = this.selectList.bind(this);
}

selectList(listId) {
this.setState({ listSelected: listId });

// Here, only the if listId Works
if (listId)
browserHistory.push('/admin/todos/' + listId);
else
browserHistory.push('/admin/todos/');
}

render() {
return (
<ListPanel
listSelected = {this.state.listSelected}
selectList = {this.selectList}
lists = {this.props.lists}
tasks = {this.props.tasks}
/>


Then The ListPanel:

renderLists() {
return this.props.lists.map((list) => (
<List
selectedItemId ={this.props.listSelected}
selectList = {() => this.props.selectList(list._id)}
key = {list._id}
list = {list}
countPendingTasks = {this.countPendingTasks(list._id)}
/>
));
}


And finally the list:

deleteThisList() {
Meteor.call('lists.remove', this.props.list._id, (err) => {
if (!err) {
this.props.selectList(null);
}
});
}

render() {
return (
<ListGroupItem
className={(this.props.list._id == this.props.selectedItemId) ? 'active' : ''}
onClick={this.props.selectList}
>
{this.props.list.name}

<Glyphicon className="pushRight red"onClick={() => this.deleteThisList()}/>
</ListGroupItem>
);
}


If I display the listId in the selectList, I have the past ID when I remove a list .. I can't find why cause I set it to null in the delete function ...

Thanks for the help.

Answer

You are overriding the argument to selectList when you are passing it to the List component, thus if you call this.props.selectList in the child component, the original function gets called with the list._id, no matter what arguments you give it.

You can fix this simply by passing the selectedList function down without binding an argument, and then just calling it with the list._id in the List component:

<List 
  selectList = {this.props.selectList}
  ...

And in the List component

<ListGroupItem 
  onClick={() => this.props.selectList(list._id)}
  ...

Now the null passed in deleteThisList function should get passed properly.

Comments