How to re-render Svelte components on demand

How to re-render the Svelte component on demand, especially how to re-render the function prop when I want to run it again

I ran into this problem yesterday: I am using the Datepicker Svelte component-it has 2 instances.

In order to provide you with more background information, I want to set a start date and an end date:

The 2 pickers

When you click the start date, the date picker appears:

The first picker

When you click the end date, a second date picker appears:

The second picker

The problem now is that based on the start date, the end date is subject to some restrictions. For example, it is logical that you cannot set the end date to be earlier than the start date.

The date picker component exposes aselectableCallbackThe function prop, called when the component is first rendered, runs for all dates in the calendar, allowing me to return false on certain dates to disable them.

<script>
let endDateSelectableCallback = date => {
  //TODO: decide if date is ok
}
</script>

<Datepicker selectableCallback={endDateSelectableCallback }>

sounds good!

Except for this function, it only runs when the component is rendered for the first time.

whenotherThe component has changed its value. Therefore, I can delete all dates before the selected start date. In addition, it must be run multiple times because users can change their minds.

So... when selecting dates on other widgets, I usedon:dateSelectedThe event is just reassigning the function I assigned toselectableCallback, CalledendDateSelectableCallback,itself.

<script>
let endDateSelectableCallback = date => {
  //TODO: decide if date is ok
}
</script>

<!-- first date picker, start date --> <Datepicker on:dateSelected={e => { endDateSelectableCallback=endDateSelectableCallback; }}> selectableCallback={endDateSelectableCallback }>

<!-- second date picker, end date --> <Datepicker selectableCallback={endDateSelectableCallback }>

This may not be the most idiomatic Svelte code, I might add onerefresh={refreshComponent}Props instead. But this may be idiomatic, because the Svelte documentation also mentions adding redundant assignments to trigger re-rendering when we update the value:

The svelte docs

I think this is a very specific pattern and may not be common. As far as I can remember, I have never encountered this problem before, so so far I am satisfied with this solution-it works.

Download mine for freeSlim Handbook


More subtle tutorials: