I’m experiencing a TypeError: Cannot read property 'serviceCategory' of null issue when the “linked page” refreshes (f5) or when the page is visited as direct traffic.
I’ve tried setting defaultProps, but it’s not triggering.
Here is my current setup:
<Link
to="/locations"
state={{
serviceCategory: "FILTER",
}}
>
linked page
const Locations = ({ location }) => {
const { state = {} } = location
const { serviceCategory } = state
const [category, setCategory] = useState(() => {
return location.state === null ? "ALL" : serviceCategory
})
}
...
Locations.defaultProps = {
location: {
state: {
serviceCategory: "ALL",
},
},
}
export default Locations
defaultProps is no where to be found in Gatsby’s documentation, so i’m thinking of a different solution.
Advertisement
Answer
The defaultProps won’t work in this case because gatsby uses @reach/router internally and props.location value is overriden by that.
You can either use a different variable name inside defaultProps or use a default value for state.
const state = location.state || { serviceCategory: 'ALL' }
Notice that
const { state = {serviceCategory:'ALL'} } = location
won’t work because default initializer in destructuring only works for undefined values and not null values. And your value is null in this case.