Change Route After API Call or On Async Redux Action
In react-application
we encounter many scenarios where we want to switch to another route based on API
response. For example when user submits a form, based on success failure we want our application to redirect him to certain specific page. Generally we accomplish this by creating aflag
variable. Which keeps track of our decision whether to redirect or not. We make one state
variable and update it, whether we want a redirection or not. Here is the code sample for the same.
Class Version
Functional Version
There is another version where we can leverage the createBrowserHistory
object of history
package which is more cleaner way of achieving this. By using this we can change our Route from async actions. To do so we have to through following process.
Step 1: Create a file and name it history.js
or history.ts
if you are using typescript. You can give any name you wanted but history
name is suitable for this file.
Step 2: Place the following content inside it:
Step 3: Navigate to your root component where you’ve added ‘Router’ . Here you have to import the history
file and pass it to the history
prop of Router.
Make sure you are importing
Router
fromreact-router-dom
not theBrowserRouter.
If you have an import like thisimport {BrowserRouter as Router} from 'react-router-dom';
change it toimport {Router} from 'react-router-dom';
.Issue if you don’t do this: Your address bar URL will change but content won’t be rendered. 😒
WHY ?🤔 Short Answer Because
BrowserRouter
ignores the history prop as it handles the history automatically for you. If you need access to the history outside of a react component, then usingRouter
should be fine👌🏻 😃
Step 4: Use history
in your action file to push routes.
You’ve successfully changed the Route from Async Redux action.