I have this code in which I use react-router-dom v6 for routing
class App extends Component {
constructor(props) {
super(props);
this.state = {
accounts: [],
};
}
componentDidMount() {
getAccounts().then(r => this.setState({ // async req
accounts: r
}));
};
render() {
return (
<Routes>
<Route path="/" element={<AppLayout accounts={this.state.accounts} />}>
<Route index element={<Navigate to={`/account/1`} />}/>
<Route path="/account/:accountId" element={<TimelinePage/>}/>
<Route path="*" element={<NotFoundPage/>}/>
</Route>
</Routes>
);
}
}
I want to redirect from the home page to /accounts/${this.state.accounts[0]}
but array this.state.accounts
is filled after an asynchronous request before mounting the App component and it turns out that the first time I render, I get to <NotFoundPage/>
. This is logical, but how can I get async data first and redirect only after that?
I made a temporary solution
<Route index element={<Navigate to={'/account/1'} />}/>`
But this does not guarantee that an element with ID 1 will always exist in the array
P.S. Array this.state.accounts
contains objects that have the numeric property accountId
. Inside the <TimelinePage/>
component I use useParams()
to get the account id and in the <AppLayout/>
component I render each element of the array