2

I'm using history.push('/, { justAddedItem: true }) to redirect to a route and let the target component know a form has been successfully submitted. It works as expected: I'm able to access this.props.history.state.justAddedItem on the Component that the / route renders.

However, when I refresh the page this.props.history.state.justAddedItem is still there! and of course it shouldn't.

In my case, I'm using this to render a success toast (I'm using react-toastify), needless to say, I don't want to show this toast on every page refresh.

If I'm in / THEN go to another route, then go back to / and refresh THEN history.state will be undefined

Component 1

componentWillReceiveProps(nextProps) {
  // addedItem comes from the redux store
  if (isEmpty(this.props.addedItem) && !isEmpty(nextProps.addedItem)) {
    this.props.clearAddedItem()
    this.props.history.push('/', { justAddedItem: true })
  }
}

Component 2

componentDidMount() {
  this.props.getItems()
  if (this.props.location.state && this.props.location.state.justAddedItem) {
    this.setState({ showAddedToast: true })
  }
}

componentDidUpdate(prevProps, prevState) {
  if (prevState.showAddedToast) {
    toast.success('Item added successfully!', {
      position: toast.POSITION.TOP_CENTER,
    })
  }
}
Julian Betancourt
  • 337
  • 2
  • 5
  • 11
  • state justAddedRecipe and justAddedItem are not the same, also can you create a codepen of your issue, state is not retained on refresh, you can check this codesandbox https://codesandbox.io/s/z2o8zo6yl4 that reproduces the expected behaviour with users – Shubham Khatri Jan 25 '18 at 06:00
  • My bad! I just edited the code so `justAddedItem` is consistent – Julian Betancourt Jan 25 '18 at 21:31
  • 1
    I know it's been a while since this question has been asked but I answered a similar one here, https://stackoverflow.com/questions/40099431/how-do-i-clear-location-state-in-react-router-on-page-reload/51292516#51292516 – Chris Gong Jul 11 '18 at 19:02

0 Answers0