'How to validate a parameter before passing it to a React hook?
Here is an example of my code. I want to get a specific element using the id from the URL (NextJS). I want to validate the id first that useElement does not run without a meaning.
const {id} = router.query
// Make sure id is not undefined
const element = useElement(id)
Approach 1
The following code snippet would make sense, but it does not work because React always needs the same number of hooks.
Error: React has detected a change in the order of Hooks called by Foo. This will lead to bugs and errors if not fixed. For more information, read the Rules of Hooks: https://reactjs.org/link/rules-of-hooks
const {id} = router.query
if (!id) {
return null
}
const element = useElement(id)
Approach 2
I also thought of validating directly inside my custom hook. However, React does not allow that.
Uncaught Error: Should have a queue. This is likely a bug in React. Please file an issue.
export function useElement(id) {
const [element, setElement] = useState()
if(!id) {
return undefined
}
useEffect(() => {
...
})
return element
}
What is the best approach to solving this issue?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
