kohshiba
kohshiba

Reputation: 357

How to update state after history.push() with withRouter?

I intend to setState after moving to another path with WithRouter. I expected that the following code both 1) redirects to the designated path and 2) updates state, however, it only executes 1). What is wrong with my codes?

What I intend to do with this method is to change the current state of pages that highlight the menu color. This happens when the page on the menu is selected or link function in a page triggered.

Class App extends .. {
  constructor(props) {
    super(props);
    this.state = {
      state: null
    };
  }
  handleState = index => e => {
    this.setState({ state: index });
  };
 render() {
  return (
    <Switch>
      <Route path="/SampleA">
        <SampleA handleState={this.handleState}>
      </Route>
      <Route path="/SampleB">
        <SampleB>
      </Route>
    </Switch>
  );
 }
}

Const SampleA = props => {
  const handlClick = () => {
    props.handleState(0);
    props.history.push({
      pathname: `/SampleB`
    });
  }
  return(
    <Button onClick={handleClick}>Go to B!</Button>
  );
}

Upvotes: 0

Views: 918

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

This might be the issue:

handleState = index => e => {
    this.setState({ state: index });
  };

should be

handleState = index => {
    this.setState({ state: index });
};

because previously handleState is a function that takes index as an argument and returns another function that expects another argument e.

Now it just takes index and updates the state.

update

this is how your function should be:

Const SampleA = props => {
  const handlClick = (e) => {
    props.handleState(e, 0);
    props.history.push({
      pathname: `/SampleB`
    });
  }
  return(
    <Button onClick={handleClick}>Go to B!</Button>
  );
}

Now the event and index are passed to the handleState function so you can use them as:

handleState = (event, index) => {
  console.log(event, index);
  this.setState({ state: index });
};

Upvotes: 1

Related Questions