widgetti / ipyreact

React for ipywidgets that just works. No webpack, no npm, no hassle
BSD 3-Clause "New" or "Revised" License
104 stars 8 forks source link

Wanted: an example of trait observe listener working with props #6

Closed paddymul closed 1 year ago

paddymul commented 1 year ago

In the following code

import ipyreact
from traitlets import Any,  Int, observe
class OtherCountWidget(ipyreact.ReactWidget):
    is_even = Any(False).tag(sync=True)
    count = Int(0).tag(sync=True)

    @observe('count')
    def _observe_value(self):
        new_val = self.count
        if new_val %2 == 0:
            self.is_even = 'True'
        else:
            self.is_even = 'False'

    _esm = """
    import confetti from "canvas-confetti";
    import * as React from "react";

    export default function({on_count, debug, count, is_even}) {
        return <div><button onClick={() => confetti() && on_count(count + 1)}>
            {count} times confetti
        </button>
        <span>count is even == {is_even.toString()} </span>
        </div>
    };"""
ocw = OtherCountWidget()
ocw

I would expect is_even to be updated based on count. the is_even listener doesn't seem to get called.

Probably related to https://github.com/jupyter-widgets/ipywidgets/issues/3756

maartenbreddels commented 1 year ago

You almost got it right!

    def _observe_value(self, change):

You missed that argument, if you are using Jupyter Lab, you probably missed the error message somewhere in the UI at the bottom.

paddymul commented 1 year ago

With your prompting, I was able to get this to work. Thank you.

I added a working example here https://github.com/widgetti/ipyreact/pull/7 . How should this be referenced in the docs?

maartenbreddels commented 1 year ago

With your prompting

I feel like your personal GPT now :P

maartenbreddels commented 1 year ago

Closed by #7