Reputation: 659
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.
Upvotes: 1
Views: 2089
Reputation: 659
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), then console.log
the params. It returned the last item of the array in the UserServices response data.
useEffect(() => {
document.title = props.match.params.subject
UserServices.getSubject(props.match.params.subject)
.then(resp => {
console.log(props.match.params.title)
if (props.match.params.title !== undefined) {
setLectures(resp.data.lectures)
mountLecture(props.match.params.title)
console.log(1)
}
else {
setLectures(resp.data.lectures)
console.log(10)
mountLecture(resp.data.lectures[0].title)
}
})
}, [])
Upvotes: 1