Hooks
Overview¶
Prefabricated hooks can be used within yourcomponents.py
to help simplify development.
Note
Looking for standard React hooks?
This package only contains Django specific hooks. Standard hooks can be found withinreactive-python/reactpy
.
Database Hooks¶
Use Query¶
Execute functions in the background and return the result, typically toread data from the Django ORM.
Thedefault postprocessor expects your query function toreturn
a DjangoModel
orQuerySet
. This needsto be changed or disabled to execute other types of queries.
Query functions can be sync or async.
1 2 3 4 5 6 7 8 91011121314151617181920212223 |
|
12345 |
|
See Interface
Name | Type | Description | Default |
---|---|---|---|
query | Callable[FuncParams,Awaitable[Inferred]]|Callable[FuncParams,Inferred] | A function that executes a query and returns some data. | N/A |
kwargs | dict[str,Any]|None | Keyword arguments to passed into thequery function. | None |
thread_sensitive | bool | Whether to run your query function in thread sensitive mode. This setting only applies to sync functions, and is turned on by default due to Django ORM limitations. | True |
postprocessor | AsyncPostprocessor|SyncPostprocessor|None | A callable that processes the querydata before it is returned. The first argument of postprocessor function must be the querydata . All proceeding arguments are optionalpostprocessor_kwargs . This postprocessor function must return the modifieddata . | None |
postprocessor_kwargs | dict[str,Any]|None | Keyworded arguments passed into thepostprocessor function. | None |
Type | Description |
---|---|
Query[Inferred] | An object containingloading /error states, yourdata (if the query has successfully executed), and arefetch callable that can be used to re-run the query. |
How can I provide arguments to my query function?
kwargs
can be provided to your query function via thekwargs=...
parameter.
1 2 3 4 5 6 7 8 910111213 |
|
How can I customize this hook's behavior?
This hook has several parameters that can be used to customize behavior.
Below are examples of values that can be modified.
Whether to run your synchronous query function in thread sensitive mode. Thread sensitive mode is turned on by default due to Django ORM limitations. See Django'ssync_to_async
docs docs for more information.
This setting only applies to sync query functions, and will be ignored for async functions.
1 2 3 4 5 6 7 8 91011121314151617 |
|
By default, automatic recursive fetching ofManyToMany
orForeignKey
fields is enabled within thedjango_query_postprocessor
. This is needed to preventSynchronousOnlyOperation
exceptions when accessing these fields within your ReactPy components.
However, if you...
- Want to use this hook to defer IO intensive tasks to be computed in the background
- Want to to utilize
use_query
with a different ORM
... then you can either set a custompostprocessor
, or disable all postprocessing behavior by modifying thepostprocessor=...
parameter. In the example below, we will set thepostprocessor
toNone
to disable postprocessing behavior.
1 2 3 4 5 6 7 8 91011121314151617181920 |
|
If you wish to create a custompostprocessor
, you will need to create a function where the first must be the querydata
. All proceeding arguments are optionalpostprocessor_kwargs
(see below). Thispostprocessor
function must return the modifieddata
.
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728 |
|
By default, automatic recursive fetching ofManyToMany
orForeignKey
fields is enabled within thedjango_query_postprocessor
. This is needed to preventSynchronousOnlyOperation
exceptions when accessing these fields within your ReactPy components.
However, if you have deep nested trees of relational data, this may not be a desirable behavior. In these scenarios, you may prefer to manually fetch these relational fields using a seconduse_query
hook.
You can disable the prefetching behavior of the defaultpostprocessor
(located atreactpy_django.utils.django_query_postprocessor
) via thepostprocessor_kwargs=...
parameter.
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829 |
|
Note: In Django's ORM design, the field name to access foreign keys ispostfixed with_set
by default.
Can I make ORM calls without hooks?
Due to Django's ORM design, database queries must be deferred using hooks. Otherwise, you will see aSynchronousOnlyOperation
exception.
TheseSynchronousOnlyOperation
exceptions may be removed in a future version of Django. However, it is best practice to always perform IO operations (such as ORM queries) via hooks to prevent performance issues.
Can I make a failed query try again?
Yes,use_mutation
can be re-executed by callingreset()
on youruse_mutation
instance.
For example, take a look atreset_event
below.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233 |
|
12345 |
|
Why does the example query function returnTodoItem.objects.all()
?
This design decision was based onApollo'suseQuery
hook, but ultimately helps avoid Django'sSynchronousOnlyOperation
exceptions.
With theModel
orQuerySet
your function returns, this hook uses thedefault postprocessor to ensure that alldeferred orlazy fields are executed.
Use Mutation¶
Modify data in the background, typically tocreate/update/delete data from the Django ORM.
Mutation functions canreturnFalse
to manually prevent yourrefetch=...
function from executing. All other returns are ignored.
Mutation functions can be sync or async.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930 |
|
12345 |
|
See Interface
Name | Type | Description | Default |
---|---|---|---|
mutation | Callable[FuncParams,bool|None]|Callable[FuncParams,Awaitable[bool|None]] | A callable that performs Django ORM create, update, or delete functionality. If this function returnsFalse , then yourrefetch function will not be used. | N/A |
thread_sensitive | bool | Whether to run the mutation in thread sensitive mode. This setting only applies to sync functions, and is turned on by default due to Django ORM limitations. | True |
refetch | Callable[...,Any]|Sequence[Callable[...,Any]]|None | A query function (the function you provide to youruse_query hook) or a sequence of query functions that need arefetch if the mutation succeeds. This is useful for refreshing data after a mutation has been performed. | None |
Type | Description |
---|---|
Mutation[FuncParams] | An object containingloading /error states, and areset callable that will setloading /error states to defaults. This object can be called to run the query. |
How can I provide arguments to my mutation function?
*args
and**kwargs
can be provided to your mutation function viamutation(...)
parameters.
1 2 3 4 5 6 7 8 910111213 |
|
How can I customize this hook's behavior?
This hook has several parameters that can be used to customize behavior.
Below are examples of values that can be modified.
Whether to run your synchronous mutation function in thread sensitive mode. Thread sensitive mode is turned on by default due to Django ORM limitations. See Django'ssync_to_async
docs docs for more information.
This setting only applies to sync query functions, and will be ignored for async functions.
1 2 3 4 5 6 7 8 910111213141516171819202122232425262728293031 |
|
Can I make ORM calls without hooks?
Due to Django's ORM design, database queries must be deferred using hooks. Otherwise, you will see aSynchronousOnlyOperation
exception.
TheseSynchronousOnlyOperation
exceptions may be removed in a future version of Django. However, it is best practice to always perform IO operations (such as ORM queries) via hooks to prevent performance issues.
Can I make a failed mutation try again?
Yes,use_mutation
can be re-executed by callingreset()
on youruse_mutation
instance.
For example, take a look atreset_event
below.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233 |
|
12345 |
|
Canuse_mutation
trigger a refetch ofuse_query
?
Yes,use_mutation
can queue a refetch of ause_query
via therefetch=...
argument.
The example below is a merge of theuse_query
anduse_mutation
examples above with the addition of ause_mutation(refetch=...)
argument.
Please note thatrefetch
will cause alluse_query
hooks that useget_items
in the current component tree will be refetched.
1 2 3 4 5 6 7 8 9101112131415161718192021222324252627282930313233343536373839404142434445 |
|
12345 |
|
User Hooks¶
Use Auth¶
Provides aNamedTuple
containingasynclogin
andasynclogout
functions.
This hook utilizes the Django's authentication framework in a way that providespersistent login.
1 2 3 4 5 6 7 8 91011121314151617181920212223 |
|
See Interface
None
Type | Description |
---|---|
UseAuthTuple | A named tuple containinglogin andlogout async functions. |
Extra Django configuration required
Your ReactPy WebSocket must utilizeAuthMiddlewareStack
in order to use this hook.
fromchannels.authimportAuthMiddlewareStack# noqa: E402application=ProtocolTypeRouter({"http":django_asgi_app,"websocket":AuthMiddlewareStack(URLRouter([REACTPY_WEBSOCKET_ROUTE])),})
Why use this instead ofchannels.auth.login
?
Thechannels.auth.*
functions cannot trigger re-renders of your ReactPy components. Additionally, they do not provide persistent authentication when used within ReactPy.
Django's authentication design requires cookies to retain login status. ReactPy is rendered via WebSockets, and browsers do not allow active WebSocket connections to modify cookies.
To work around this limitation, whenuse_auth().login()
is called within your application, ReactPy performs the following process...
- The server authenticates the user into the WebSocket session
- The server generates a temporary login token linked to the WebSocket session
- The server commands the browser to fetch the login token via HTTP
- The client performs the HTTP request
- The server returns the HTTP response, which contains all necessary cookies
- The client stores these cookies in the browser
This ultimately results in persistent authentication which will be retained even if the browser tab is refreshed.
Use User¶
Shortcut that returns the WebSocket or HTTP connection'sUser
.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
AbstractUser | A DjangoUser , which can also be anAnonymousUser . |
Use User Data¶
Store or retrieve adict
containing arbitrary data specific to the connection'sUser
.
This hook is useful for storing user-specific data, such as preferences, settings, or any generic key-value pairs.
User data saved with this hook is stored within theREACTPY_DATABASE
.
1 2 3 4 5 6 7 8 91011121314151617181920 |
|
See Interface
Name | Type | Description | Default |
---|---|---|---|
default_data | None|dict[str,Callable[[],Any]|Callable[[],Awaitable[Any]]|Any] | A dictionary containing{key:default_value} pairs. For computationally intensive defaults, yourdefault_value can be sync or async functions that return the value to set. | None |
save_default_data | bool | IfTrue ,default_data values will automatically be stored within the database if they do not exist. | False |
Type | Description |
---|---|
UserData | ANamedTuple containing aQuery andMutation objects used to access/modify user data. Read theuse_query anduse_mutation docs for more details. |
How do I set default values?
You can configure default user data via thedefault_data
parameter.
This parameter accepts a dictionary containing a{key:default_value}
pairs. For computationally intensive defaults, yourdefault_value
can be sync or async functions that return the value to set.
1 2 3 4 5 6 7 8 91011121314151617181920212223242526 |
|
Communication Hooks¶
Use Channel Layer¶
Subscribe to aDjango Channels layer to send/receive messages.
Layers are a multiprocessing-safe communication system that allows you to send/receive messages between different parts of your application.
This is often used to create chat systems, synchronize data between components, or signal re-renders from outside your components.
1 2 3 4 5 6 7 8 91011121314151617181920212223 |
|
See Interface
Name | Type | Description | Default |
---|---|---|---|
name | str|None | The name of the channel to subscribe to. If you define agroup_name , you can keepname undefined to auto-generate a unique name. | None |
group_name | str|None | If configured, any messages sent within this hook will be broadcasted to all channels in this group. | None |
group_add | bool | IfTrue , the channel will automatically be added to the group when the component mounts. | True |
group_discard | bool | IfTrue , the channel will automatically be removed from the group when the component dismounts. | True |
receiver | AsyncMessageReceiver|None | An async function that receives amessage:dict from a channel. If more than one receiver waits on the same channel name, a random receiver will get the result. | None |
layer | str | The channel layer to use. This layer must be defined insettings.py:CHANNEL_LAYERS . | 'default' |
Type | Description |
---|---|
AsyncMessageSender | An async callable that can send amessage:dict . |
Extra Django configuration required
In order to use this hook, you will need to configure Django to enable channel layers.
TheDjango Channels documentation has information on what steps you need to take.
In summary, you will need to:
Install
redis
on your machine.Run the following command to install
channels-redis
in your Python environment.pipinstallchannels-redis
Configure your
settings.py
to useRedisChannelLayer
as your layer backend.CHANNEL_LAYERS={"default":{"BACKEND":"channels_redis.core.RedisChannelLayer","CONFIG":{"hosts":[("127.0.0.1",6379)],},},}
How do I broadcast a message to multiple components?
If more than one receiver waits on the same channel, a random one will get the result.
To get around this, you can define agroup_name
to broadcast messages to all channels within a specific group. If you do not define a channelname
while using groups, ReactPy will automatically generate a unique channel name for you.
In the example below, all messages sent by thesender
component will be received by allreceiver
components that exist (across every active client browser).
1 2 3 4 5 6 7 8 91011121314151617181920212223242526272829303132333435363738394041 |
|
How do I signal a re-render from something that isn't a component?
There are occasions where you may want to signal a re-render from something that isn't a component, such as a Django model signal.
In these cases, you can use theuse_channel_layer
hook to receive a signal within your component, and then use theget_channel_layer().send(...)
to send the signal.
In the example below, the sender will signal every timeExampleModel
is saved. Then, when the receiver gets this signal, it explicitly callsset_message(...)
to trigger a re-render.
1 2 3 4 5 6 7 8 910111213141516171819 |
|
1 2 3 4 5 6 7 8 9101112131415 |
|
Connection Hooks¶
Use Connection¶
Returns the active connection, which is either a DjangoWebSocket or aHTTP Request.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
Connection | An object that contains acarrier (WebSocket orHttpRequest ),scope , andlocation . |
Use Scope¶
Shortcut that returns the WebSocket or HTTP connection'sscope.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
MutableMapping[str,Any] | The connection'sscope . |
Use Location¶
Shortcut that returns the browser's currentLocation
.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
Location | An object containing the current URL'spathname andsearch query. |
Use Origin¶
Shortcut that returns the WebSocket or HTTP connection'sorigin
.
You can expect this hook to provide strings such ashttp://example.com
.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
str|None | A string containing the browser's current origin, obtained from WebSocket or HTTP headers (if available). |
Use Root ID¶
Shortcut that returns the root component'sid
from the WebSocket or HTTP connection.
The root ID is a randomly generateduuid4
. It is notable to mention that it is persistent across the current connection. Theuuid
is reset only when the page is refreshed.
This is useful when used in combination withuse_channel_layer
to send messages to a specific component instance, and/or retain a backlog of messages in case that component is disconnected viause_channel_layer(...,group_discard=False)
.
1 2 3 4 5 6 7 8 910 |
|
See Interface
None
Type | Description |
---|---|
str | A string containing the root component'sid . |
Use Re-render¶
Returns a function that can be used to trigger a re-render of the entire component tree.
1 2 3 4 5 6 7 8 9101112131415 |
|
See Interface
None
Type | Description |
---|---|
Callable[[],None] | A function that triggers a re-render of the entire component tree. |