I'm extremely new to ReactJs and Redux. I am able to set up a simple app with multiple React components dispatching actions to the Redux store on button clicks, dropdown selections, etc. But one thing I can't seem to figure out is, how would you go about initializing an app's state based on a URL parameter?
For example, let's say you have a user profile page, and depending on the "userid" URL parameter, you want to display different user data on the page when it first loads. What I initially thought was to use the "componentDidMount" lifecycle method and dispatch an action to the store - maybe something like "loadUser(userid)". But this seems like overkill - is there a universally-accepted way of populating a store from some initial value?
If you are needing route specific variables then its probably easiest (and best practice) to use the route params to initialize state and rerun actions.
If you use class based components loadUser(userId) will need to be in both componentDidMount and componentDidUpdate.
For functional components there is React hook useEffect() instead (which seems to be becoming best/better practice these days).
For Example:
If you are using react-router-dom in your routes.js/app.js you will have a route such as:
<Route path='/some/path/:userid' component={someComponent}/>
Then use props.match.params and useEffect with the userid as a dependency:
import React , {useEffect} from 'react'
import {connect} from 'react-redux'
import * as actions from 'path/to/redux/actions'
// destructure `match.params.userid`, redux `user` and redux action `loadUser` from props
const someComponent = ({ match:{params:{userid}} , user , loadUser}) => {
useEffect(()=>{
userid && loadUser(userid)
},[loadUser , userid]) // runs after first mount and every time userid changes
return <div>{user && user.id}</div>
}
connect(
({user})=>({user}),
actions
)(someComponent)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With