Is there any way to define a signal inside a route component?
Is there any way to define a signal inside a route component? I am trying to do it but an error raises
Error:
Code:
3 Replies
Based on the documentation, it seems like you're trying to use Preact Signals inside an async route component. However, the error message you're seeing suggests that the
useSignal
hook is being called outside of a Preact component's render method.
In Preact (and React), hooks like useSignal
must be called during the rendering of a component. They cannot be called in an asynchronous function or outside of a component's render method.
Here's an example of how to use useSignal
inside a component, as per the documentation:
In your case, you're trying to use useSignal
inside an async function, which is not allowed. You should move the useSignal
calls inside the component's render method.
If you need to fetch data asynchronously, you can do so outside of the component and pass the data as a prop to the component. Alternatively, you can use an effect hook (like useEffect
in React) to fetch data after the component has been rendered, and then update the state with the fetched data.
Please note that this advice is based on general React/Preact principles and not explicitly stated in the documentation.@EGamalielGZ Async routes are not truly Preact components, but rather functions that happen to return JSX. Because of that the component context that hooks require is not set up and the error is thrown. To address this use the
signal()
function instead of useSignal()
Thanks for the help 😄