I am a bit confused here and unluckily I couldn't get any solution on the discord channel of svelte so here I go...
I have a rather basic example of two classes, let them be App
and Comp
.
App
creates a Comp
instance and then updates this instance's value
after a button click.
The Comp instance should set this value to a different variable (inputValue
) and upon changing that variable it should fire validate(inputValue)
which is reactive. Here is a REPL: https://svelte.dev/repl/1df2eb0e67b240e9b1449e52fb26eb14?version=3.25.1
App.svelte:
<script>
import Comp from './Comp.svelte';
let value = 'now: ' + Date.now();
function clickHandler(e) {
value = 'now ' + Date.now();
}
</script>
<Comp
bind:value={value}
/>
<button type="button" on:click={clickHandler}>change value</button>
Comp.svelte:
<script>
import { onMount } from 'svelte';
export let value;
let rendered = false;
let inputValue = '';
$: validate(inputValue); // This doesn't execute. Why?
function validate(val) {
console.log('validation:', val);
}
onMount(() => {
rendered = true;
});
$: if (rendered) {
updateInputValue(value);
}
function updateInputValue(val) {
console.log('updateInputValue called!');
if (!value) {
inputValue = '';
}
else {
inputValue = value;
}
}
</script>
<input type="text" bind:value={inputValue}>
So as soon as the value is changed:
- The reactive
if (rendered) {...}
condition is called updateInputValue
is called andinputValue
is changed. HTML input element is updated to this value.validate(inputValue)
never reacts to this change - WHY?
If I omit the extra call to the updateInputValue
function in the reactive if (rendered)
condition and put updateInputValue
function body's code directly to the condition, then validate(inputValue)
is triggered correctly, i.e.:
// works like this
$: if (rendered) {
if (!value) {
inputValue = '';
}
else {
inputValue = value;
}
}
So how come it doesn't work when updated in the function?