how to implement a progress bar that renders multiple times when a function is running? #1194
-
I am trying to understand the basics of progress bar in reactpy. I want the progress bar to update itself multiple times when a button is clicked. I try to implement a dummy example using bootstrap progress bar. The basic idea is that if the "Count" button is clicked, it will run a function that yields a number (0,20,40,60,80,100) every second. I want the progress bar to update for every second. But obviously, my approach is wrong, as the event handler function will only render once after it runs all the codes. How to implement this correctly? Thanks. from reactpy import component, html, use_state, hooks
import time
def count_sec():
for i in [0, 20, 40, 60, 80, 100]:
yield i
time.sleep(1)
@component
def progress_bar_app():
data, set_data = hooks.use_state(0)
def handle_count_button(event):
for i in count_sec():
set_data(i)
r = html.div(
{
'class_name': 'container-sm',
},
html.button({"on_click": handle_count_button}, "Count"),
html.br(),
html.br(),
html.div(
{
'class_name': 'progress',
'role': 'progressbar',
'aria-valuenow':'25',
'aria-valuemin':'0',
'aria-valuemax':'100',
'aria-label': 'Basic example'
},
html.div(
{
'class_name': 'progress-bar',
'style': {'width': f"{data}%"},
}
)
)
) |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
There are two common approaches you can take to update a status bar
@component
def progress_bar_app():
percentage, set_percentage = hooks.use_state(0)
@hooks.use_effect
async def update_percentage():
while True:
await sleep(1)
# Retrieve the current percentage from something like a database or redis.
current = await get_percentage()
set_percentage(current)
return ...
This is useful if you have a parent component that is actually performing the "progression actions". @component
def progress_bar_app(percentage):
return ...
@component
def parent():
return html.div(
progress_bar_app(percentage=100),
) |
Beta Was this translation helpful? Give feedback.
There are two common approaches you can take to update a status bar
redis
ormysql
and have your component poll for it viause_effect
prop
(get the actual value from a parent component).This is useful if you have a parent component that is a…