Skip to content
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

How to refresh a component from another component ? #730

Open
1 task done
CedricRaison opened this issue Aug 25, 2024 · 1 comment
Open
1 task done

How to refresh a component from another component ? #730

CedricRaison opened this issue Aug 25, 2024 · 1 comment

Comments

@CedricRaison
Copy link

CedricRaison commented Aug 25, 2024

I have a ListPostView component which list my posts.

class ListPostView(UnicornView):
    posts = []

    def mount(self):
        self.posts = list(Post.objects.all().order_by('-created_at'))

I have another component which is a form to create a new post.

I would like after saving a new post to refresh my ListPostView to display my new post.

class CreatePostView(UnicornView):
    content = ""

    def save(self):
        if self.content:
            post = Post.objects.create(content=self.content)
            self.content = ""
            # refresh ListPostView so it can show my new post.

Code of Conduct

  • I agree to follow this project's Code of Conduct
@pa-hqt
Copy link

pa-hqt commented Nov 25, 2024

Hi,
what helped me to work around certain circumstances in the past, was the possibility to call some JavaScript function from the python component. Django-unicorn adds a list of JS calls to the response that will be executed at the client and can for example trigger to call a method of another unicorn component (what causes a new request to the server).

documentation:
https://www.django-unicorn.com/docs/javascript/#call-javascript-from-view

class SourceCheckboxView(UnicornView):

    is_checked: bool = False
    """Check state of the HTML input"""

    def toggle_check_state(self):
        self.is_checked = not self.is_checked
        # WORKAROUND: JavaScript functions triggers update of the other component, when request is responded (time lag, because of round-trip)
        self.call("Unicorn.call", "compare-list", "reload_state")
  • "self.call()" adds the advice to the response of the current request
  • "Unicorn.call" is a global JavaScript function that is available
  • "compare-list" is the name of another unicorn component that is available on the same page as source-checkbox
  • "reload_state" is a method of the other component

it helps to observe the Dev-Tools > network console of your browser to see, what is happening. Investigate the XHR calls (requests) and response data that are received

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants