Skip to content

Accept a function as initial value for use_state #46

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion reacton/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -766,7 +766,9 @@ def get_widget(el: Element):
raise KeyError(f"Element {el} not found in all known widgets") # for the component {context.widgets}")


def use_state(initial: T, key: str = None, eq: Callable[[Any, Any], bool] = None) -> Tuple[T, Callable[[Union[T, Callable[[T], T]]], None]]:
def use_state(
initial: Union[T, Callable[[], T]], key: str = None, eq: Callable[[Any, Any], bool] = None
) -> Tuple[T, Callable[[Union[T, Callable[[T], T]]], None]]:
"""Returns a `(value, setter)` tuple that is used to manage state in a component.

This function can only be called from a component function.
Expand Down Expand Up @@ -1261,6 +1263,9 @@ def use_state(self, initial, key: str = None, eq: Callable[[Any, Any], bool] = N
key = str(self.context.state_index)
self.context.state_index += 1
if key not in self.context.state:
if callable(initial):
initial = initial()

self.context.state[key] = initial
if isinstance(initial, (list, dict, set)):
self.context.state_metadata[key] = len(initial)
Expand Down
26 changes: 26 additions & 0 deletions reacton/core_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1620,6 +1620,32 @@ def update_click(click):
rc.close()


def test_use_state_initial_function():
initial_func = unittest.mock.Mock()
initial_func.return_value = 10

@react.component
def ButtonClick(label="Hi"):
clicks, set_clicks = react.use_state(initial_func)

def update_click(click):
return click + 1

return w.Button(description=f"{label}: Clicked {clicks} times", on_click=lambda: set_clicks(update_click))

clicker, rc = react.render_fixed(ButtonClick())

initial_func.assert_called_once()
assert clicker.description == "Hi: Clicked 10 times"

clicker.click()

initial_func.assert_called_once()
assert clicker.description == "Hi: Clicked 11 times"

rc.close()


def test_use_ref():
last = None

Expand Down