I am relativity new to react/redux. There for I want to ask a (perhaps a philosophic) question.
Is it ok to to dispatch an action (e.g. to trigger an api-call) on componentDidMount
of a react component?
If not, why and where should I dispatch the action?
If yes, then no further questions? :)
Yes, dispatching an action on
componentDidMount()
is OK, and even the recommended thing to do since it will not slow down the initial UI render.Since the function runs after the component has initially rendered, keep in mind that you may have sometime between the moment the component is rendered, and the moment you receive the data from the api call.
According to the official React documentation,
componentDidMount
is exactly the right place to do so:— Official React Documentation for
componentDidMount()
When using routes another recommended way to dispatch an action would be the routes-method "onEnter". This is in order to make the component not dependent from actions (or api-calls).
I personally think both methods (componentDidMount vs. onEnter) are ok. It is left to the programmer to choose which solution is best for his application.
Yes, you should definately use the componentDidMount hook.
A typical use case might be :
I know its a bit long, but I was working myself on this type of problem for a while, so I thought I would share the following pattern ;)
When the component mounts then a fetch data action is triggered. An 'isFetching' value in the application state determines whether the spinner is shown or not (I think i used 'advanced-loader' or some such library)
Then in the store the FETCH_DATA triggers a request :
The request would look something like this :
Upon completion it would then dispatch another action.
Going back to the store, the second action is caught and the isFetching flag is set to false, then the application data is handled.
.... so this typical use case uses two 'actions', the first action being triggered from the componentDidMount method, and the second action is triggered after the request finishes.
Hope this pattern helps :)