2

In my componentDidMount, I'm fetching data and then using setState to store that data. In my render, I'm conditionally rendering/redirecting to a component based on my state but then I need to clear my state so that it doesn't get stuck in an infinite loop of redirect. But when I invoke the function to redirect in my render, I get a warning Cannot update during an existing state transition (such as within render). How should I get around this?

componentDidMount() {
  let branchKeyTest = 'key_test_b'  
  branch.init(branchKeyTest, (err, data) => {
    this.setState({ redirectPath: data })
  }
  this.setState({ isLoading: false })
}) 


redirectToPath = (path) => {
    const { history } = this.props;
    history.push(path);
    this.setState({ redirectPath: null })   
  }

render() {
    const { isLoading, redirectPath } = this.state;
    const { token, location } = this.props;
    const loggedIn = !!token;


    if (!isLoading && loggedIn && (redirectPath != null)) {
      switch (redirectPath.link_type) {
        case 'new_release':
            this.redirectToPath(`/releases/releaseinfo/${redirectPath.id}`)
          break;
        default:
          return;
      }
    }

    if (!isLoading) {
      return (
        <div>Done Loading</div>
      );

    }
    else {
      return (<h1>Loading...</h1>)
    }
 }
jj008
  • 1,033
  • 3
  • 23
  • 48
  • Have you try to redirect in componentDidMount based on your response. ? – Qubaish Bhatti Dec 18 '19 at 06:24
  • 1
    Does this answer your question? [ReactJS: Warning: setState(...): Cannot update during an existing state transition](https://stackoverflow.com/questions/37387351/reactjs-warning-setstate-cannot-update-during-an-existing-state-transiti) – keikai Dec 18 '19 at 06:24
  • @QubaishBhatti I tried using a callback after `setState` but my token is not saved yet so it's not recognizing the user is logged in immediately. How can I ensure to redirect after the token prop is available? – jj008 Dec 18 '19 at 19:30

0 Answers0