forked from reactive-python/reactpy-django
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathuse_mutation_query_refetch.py
45 lines (34 loc) · 1.24 KB
/
use_mutation_query_refetch.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from reactpy import component, html
from example.models import TodoItem
from reactpy_django.hooks import use_mutation, use_query
def get_items():
return TodoItem.objects.all()
def add_item(text: str):
TodoItem(text=text).save()
@component
def todo_list():
item_query = use_query(get_items)
item_mutation = use_mutation(add_item, refetch=get_items)
def submit_event(event):
if event["key"] == "Enter":
item_mutation(text=event["target"]["value"])
# Handle all possible query states
if item_query.loading:
rendered_items = html.h2("Loading...")
elif item_query.error or not item_query.data:
rendered_items = html.h2("Error when loading!")
else:
rendered_items = html.ul(html.li(item.text, key=item.pk) for item in item_query.data)
# Handle all possible mutation states
if item_mutation.loading:
mutation_status = html.h2("Adding...")
elif item_mutation.error:
mutation_status = html.h2("Error when adding!")
else:
mutation_status = html.h2("Mutation done.")
return html.div(
html.label("Add an item:"),
html.input({"type": "text", "on_key_down": submit_event}),
mutation_status,
rendered_items,
)