I have a functional component where I am trying to access URL params that have been namespaced in react-router via a hook.
useEffect(() => {
document.title = props.match.params.subject
UserServices.getSubject(props.match.params.subject)
.then(resp => {
if (resp.data.lectures !== undefined) {
setLectures(resp.data.lectures)
mountLecture(resp.data.lectures[0].title)
}
})
}, [])
useEffect(() => {
if(props.match.params.title) mountLecture(props.match.params.title)
else mountLecture(lectures[0].title)
}, [props.match.params])
However, it keeps telling me can't read the property title of undefined
, even though it comes out in a console log.
So I decided to combine the useEffect hooks since I only needed them to run once.
Then I used the if statement to check the params before calling 'setLectures()'. Something interesting to note, when I called
setLectures()
before the if statement (to be DRY), thenconsole.log
the params. It returned the last item of the array in the UserServices response data.