Movatterモバイル変換


[0]ホーム

URL:


Skip to content

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
fromchannels.dbimportdatabase_sync_to_asyncfromreactpyimportcomponent,htmlfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_queryasyncdefget_items():returnawaitdatabase_sync_to_async(TodoItem.objects.all)()@componentdeftodo_list():item_query=use_query(get_items)ifitem_query.loading:rendered_items=html.h2("Loading...")elifitem_query.errorornotitem_query.data:rendered_items=html.h2("Error when loading!")else:rendered_items=html.ul([html.li(item.text,key=item.pk)foriteminitem_query.data])returnhtml.div("Rendered items: ",rendered_items)
12345
fromdjango.db.modelsimportCharField,ModelclassTodoItem(Model):text:CharField=CharField(max_length=255)
See Interface

NameTypeDescriptionDefault
queryCallable[FuncParams,Awaitable[Inferred]]|Callable[FuncParams,Inferred]A function that executes a query and returns some data.N/A
kwargsdict[str,Any]|NoneKeyword arguments to passed into thequery function.None
thread_sensitiveboolWhether 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
postprocessorAsyncPostprocessor|SyncPostprocessor|NoneA 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_kwargsdict[str,Any]|NoneKeyworded arguments passed into thepostprocessor function.None

TypeDescription
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
fromreactpyimportcomponentfromreactpy_django.hooksimportuse_querydefexample_query(value:int,other_value:bool=False):...@componentdefmy_component():query=use_query(example_query,{"value":123,"other_value":True})returnstr(query.data)
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
fromreactpyimportcomponentfromreactpy_django.hooksimportuse_querydefexecute_thread_safe_operation():"""This is an example query function that does some thread-safe operation."""@componentdefmy_component():query=use_query(execute_thread_safe_operation,thread_sensitive=False)ifquery.loadingorquery.error:returnNonereturnstr(query.data)

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...

  1. Want to use this hook to defer IO intensive tasks to be computed in the background
  2. Want to to utilizeuse_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
fromreactpyimportcomponentfromreactpy_django.hooksimportuse_querydefexecute_io_intensive_operation():"""This is an example query function that does something IO intensive."""@componentdefmy_component():query=use_query(execute_io_intensive_operation,postprocessor=None,)ifquery.loadingorquery.error:returnNonereturnstr(query.data)

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
fromreactpyimportcomponentfromreactpy_django.hooksimportuse_querydefmy_postprocessor(data,example_kwarg=True):ifexample_kwarg:returndatareturndict(data)defexecute_io_intensive_operation():"""This is an example query function that does something IO intensive."""@componentdefmy_component():query=use_query(execute_io_intensive_operation,postprocessor=my_postprocessor,postprocessor_kwargs={"example_kwarg":False},)ifquery.loadingorquery.error:returnNonereturnstr(query.data)

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
fromreactpyimportcomponentfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_querydefget_model_with_relationships():"""This is an example query function that gets `MyModel` which has a ManyToMany field, and    additionally other models that have formed a ForeignKey association to `MyModel`.    ManyToMany Field: `many_to_many_field`    ForeignKey Field: `foreign_key_field_set`    """returnTodoItem.objects.get(id=1)@componentdefmy_component():query=use_query(get_model_with_relationships,postprocessor_kwargs={"many_to_many":False,"many_to_one":False},)ifquery.loadingorquery.errorornotquery.data:returnNone# By disabling `many_to_many` and `many_to_one`, accessing these fields will now# generate a `SynchronousOnlyOperation` exceptionreturnf"{query.data.many_to_many_field}{query.data.foriegn_key_field_set}"

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
fromreactpyimportcomponent,htmlfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_mutationdefadd_item(text:str):TodoItem(text=text).save()@componentdeftodo_list():item_mutation=use_mutation(add_item)defreset_event(event):item_mutation.reset()defsubmit_event(event):ifevent["key"]=="Enter":item_mutation(text=event["target"]["value"])ifitem_mutation.loading:mutation_status=html.h2("Adding...")elifitem_mutation.error:mutation_status=html.button({"on_click":reset_event},"Error: Try again!")else:mutation_status=html.h2("Mutation done.")returnhtml.div(html.label("Add an item:"),html.input({"type":"text","on_key_down":submit_event}),mutation_status,)
12345
fromdjango.db.modelsimportCharField,ModelclassTodoItem(Model):text:CharField=CharField(max_length=255)
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
fromreactpyimportcomponent,htmlfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_mutationasyncdefadd_item(text:str):awaitTodoItem(text=text).asave()@componentdeftodo_list():item_mutation=use_mutation(add_item)defsubmit_event(event):ifevent["key"]=="Enter":item_mutation(text=event["target"]["value"])ifitem_mutation.loading:mutation_status=html.h2("Adding...")elifitem_mutation.error:mutation_status=html.h2("Error when adding!")else:mutation_status=html.h2("Mutation done.")returnhtml.div(html.label("Add an item:"),html.input({"type":"text","on_key_down":submit_event}),mutation_status,)
12345
fromdjango.db.modelsimportCharField,ModelclassTodoItem(Model):text:CharField=CharField(max_length=255)
See Interface

NameTypeDescriptionDefault
mutationCallable[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_sensitiveboolWhether 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
refetchCallable[...,Any]|Sequence[Callable[...,Any]]|NoneA 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

TypeDescription
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
fromreactpyimportcomponentfromreactpy_django.hooksimportuse_mutationdefexample_mutation(value:int,other_value:bool=False):...@componentdefmy_component():mutation=use_mutation(example_mutation)mutation(123,other_value=True)
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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_mutationdefexecute_thread_safe_mutation(text):"""This is an example mutation function that does some thread-safe operation."""@componentdefmy_component():item_mutation=use_mutation(execute_thread_safe_mutation,thread_sensitive=False,)defsubmit_event(event):ifevent["key"]=="Enter":item_mutation(text=event["target"]["value"])ifitem_mutation.loadingoritem_mutation.error:mutation_status=html.h2("Doing something...")elifitem_mutation.error:mutation_status=html.h2("Error!")else:mutation_status=html.h2("Done.")returnhtml.div(html.input({"type":"text","on_key_down":submit_event}),mutation_status,)
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
fromreactpyimportcomponent,htmlfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_mutationdefadd_item(text:str):TodoItem(text=text).save()@componentdeftodo_list():item_mutation=use_mutation(add_item)defreset_event(event):item_mutation.reset()defsubmit_event(event):ifevent["key"]=="Enter":item_mutation(text=event["target"]["value"])ifitem_mutation.loading:mutation_status=html.h2("Adding...")elifitem_mutation.error:mutation_status=html.button({"on_click":reset_event},"Error: Try again!")else:mutation_status=html.h2("Mutation done.")returnhtml.div(html.label("Add an item:"),html.input({"type":"text","on_key_down":submit_event}),mutation_status,)
12345
fromdjango.db.modelsimportCharField,ModelclassTodoItem(Model):text:CharField=CharField(max_length=255)
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
fromreactpyimportcomponent,htmlfromexample.modelsimportTodoItemfromreactpy_django.hooksimportuse_mutation,use_querydefget_items():returnTodoItem.objects.all()defadd_item(text:str):TodoItem(text=text).save()@componentdeftodo_list():item_query=use_query(get_items)item_mutation=use_mutation(add_item,refetch=get_items)defsubmit_event(event):ifevent["key"]=="Enter":item_mutation(text=event["target"]["value"])# Handle all possible query statesifitem_query.loading:rendered_items=html.h2("Loading...")elifitem_query.errorornotitem_query.data:rendered_items=html.h2("Error when loading!")else:rendered_items=html.ul(html.li(item.text,key=item.pk)foriteminitem_query.data)# Handle all possible mutation statesifitem_mutation.loading:mutation_status=html.h2("Adding...")elifitem_mutation.error:mutation_status=html.h2("Error when adding!")else:mutation_status=html.h2("Mutation done.")returnhtml.div(html.label("Add an item:"),html.input({"type":"text","on_key_down":submit_event}),mutation_status,rendered_items,)
12345
fromdjango.db.modelsimportCharField,ModelclassTodoItem(Model):text:CharField=CharField(max_length=255)

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
fromdjango.contrib.authimportget_user_modelfromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_auth,use_user@componentdefmy_component():auth=use_auth()user=use_user()asyncdeflogin_user(event):new_user,_created=awaitget_user_model().objects.aget_or_create(username="ExampleUser")awaitauth.login(new_user)asyncdeflogout_user(event):awaitauth.logout()returnhtml.div(f"Current User:{user}",html.button({"onClick":login_user},"Login"),html.button({"onClick":logout_user},"Logout"),)
See Interface

None

TypeDescription
UseAuthTupleA 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...

  1. The server authenticates the user into the WebSocket session
  2. The server generates a temporary login token linked to the WebSocket session
  3. The server commands the browser to fetch the login token via HTTP
  4. The client performs the HTTP request
  5. The server returns the HTTP response, which contains all necessary cookies
  6. 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_user@componentdefmy_component():user=use_user()returnhtml.div(user.username)
See Interface

None

TypeDescription
AbstractUserA 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_user_data@componentdefmy_component():query,mutation=use_user_data()defon_submit(event):ifevent["key"]=="Enter"andquery.data:new_key=str(len(query.data))mutation({**query.data,new_key:event["target"]["value"]})returnhtml.div(html.div(f"Data:{query.data}"),html.div(f"Loading:{query.loading|mutation.loading}"),html.div(f"Error(s):{query.error}{mutation.error}"),html.input({"on_key_press":on_submit}),)
See Interface

NameTypeDescriptionDefault
default_dataNone|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_databoolIfTrue,default_data values will automatically be stored within the database if they do not exist.False

TypeDescription
UserDataANamedTuple 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_user_data@componentdefmy_component():user_data=use_user_data(default_data={"basic_example":"123","computed_example_sync":sync_default,"computed_example_async":async_default,})returnhtml.div(html.div(f"Data:{user_data.query.data}"),)defsync_default():return...asyncdefasync_default():return...

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
fromreactpyimportcomponent,hooks,htmlfromreactpy_django.hooksimportuse_channel_layer@componentdefmy_component():asyncdefreceive_message(message):set_message(message["text"])asyncdefsend_message(event):ifevent["key"]=="Enter":awaitsender({"text":event["target"]["value"]})message,set_message=hooks.use_state("")sender=use_channel_layer("my-channel-name",receiver=receive_message)returnhtml.div(f"Received:{message}",html.br(),"Send: ",html.input({"type":"text","onKeyDown":send_message}),)
See Interface

NameTypeDescriptionDefault
namestr|NoneThe name of the channel to subscribe to. If you define agroup_name, you can keepname undefined to auto-generate a unique name.None
group_namestr|NoneIf configured, any messages sent within this hook will be broadcasted to all channels in this group.None
group_addboolIfTrue, the channel will automatically be added to the group when the component mounts.True
group_discardboolIfTrue, the channel will automatically be removed from the group when the component dismounts.True
receiverAsyncMessageReceiver|NoneAn 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
layerstrThe channel layer to use. This layer must be defined insettings.py:CHANNEL_LAYERS.'default'

TypeDescription
AsyncMessageSenderAn 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:

  1. Installredis on your machine.

  2. Run the following command to installchannels-redis in your Python environment.

    pipinstallchannels-redis
  3. Configure yoursettings.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
fromreactpyimportcomponent,hooks,htmlfromreactpy_django.hooksimportuse_channel_layer@componentdefmy_sender_component():sender=use_channel_layer(group_name="my-group-name")asyncdefsubmit_event(event):ifevent["key"]=="Enter":awaitsender({"text":event["target"]["value"]})returnhtml.div("Message Sender: ",html.input({"type":"text","onKeyDown":submit_event}),)@componentdefmy_receiver_component_1():message,set_message=hooks.use_state("")asyncdefreceive_event(message):set_message(message["text"])use_channel_layer(group_name="my-group-name",receiver=receive_event)returnhtml.div(f"Message Receiver 1:{message}")@componentdefmy_receiver_component_2():message,set_message=hooks.use_state("")asyncdefreceive_event(message):set_message(message["text"])use_channel_layer(group_name="my-group-name",receiver=receive_event)returnhtml.div(f"Message Receiver 2:{message}")
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
fromasgiref.syncimportasync_to_syncfromchannels.layersimportget_channel_layerfromdjango.db.modelsimportModelfromdjango.db.models.signalsimportpre_savefromdjango.dispatchimportreceiverclassExampleModel(Model):...@receiver(pre_save,sender=ExampleModel)defmy_sender_signal(sender,instance,**kwargs):layer=get_channel_layer()# Example of sending a message to a channelasync_to_sync(layer.send)("my-channel-name",{"text":"Hello World!"})# Example of sending a message to a group channelasync_to_sync(layer.group_send)("my-group-name",{"text":"Hello World!"})
 1 2 3 4 5 6 7 8 9101112131415
fromreactpyimportcomponent,hooks,htmlfromreactpy_django.hooksimportuse_channel_layer@componentdefmy_receiver_component():message,set_message=hooks.use_state("")asyncdefreceive_event(message):set_message(message["text"])use_channel_layer("my-channel-name",receiver=receive_event)returnhtml.div(f"Message Receiver:{message}")

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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_connection@componentdefmy_component():connection=use_connection()returnhtml.div(str(connection))
See Interface

None

TypeDescription
ConnectionAn 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_scope@componentdefmy_component():scope=use_scope()returnhtml.div(str(scope))
See Interface

None

TypeDescription
MutableMapping[str,Any]The connection'sscope.

Use Location

Shortcut that returns the browser's currentLocation.

 1 2 3 4 5 6 7 8 910
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_location@componentdefmy_component():location=use_location()returnhtml.div(location.pathname+location.search)
See Interface

None

TypeDescription
LocationAn 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_origin@componentdefmy_component():origin=use_origin()returnhtml.div(originor"No origin")
See Interface

None

TypeDescription
str|NoneA 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
fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_root_id@componentdefmy_component():root_id=use_root_id()returnhtml.div(f"Root ID:{root_id}")
See Interface

None

TypeDescription
strA 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
fromuuidimportuuid4fromreactpyimportcomponent,htmlfromreactpy_django.hooksimportuse_rerender@componentdefmy_component():rerender=use_rerender()defon_click():rerender()returnhtml.div(f"UUID:{uuid4()}",html.button({"onClick":on_click},"Rerender"))
See Interface

None

TypeDescription
Callable[[],None]A function that triggers a re-render of the entire component tree.

Last update:December 29, 2024
Authors:Mark Bakhit

[8]ページ先頭

©2009-2025 Movatter.jp