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>)
}
}