Las variables reactivas no funcionan en mi aplicación esbelta. Cuando los registro en mi consola, no están undefined .
Tengo en App.svelte el siguiente código relevante
<script> let polls = [ { question: "JavaScript or Python?", answerA: "JavaScript", answerB: "Python", votesA: 16, votesB: 4 } ] const handleVote = e => {/* increase vote A or vote B by 1*/} </script> <PollsList {polls} on:vote={handleVote}/> En PollsList.svelte tengo el siguiente código relevante
<script> export let polls = []; </script> {#each polls as poll (poll.id)} <PollItem {poll} on:vote/> {/each} y en mi PollItem.svelte tengo el siguiente código relevante
<script> import {createEventDispatcher} from "svelte"; const disptach = createEventDispatcher(); export let poll; $: totalVotes = poll.votesA + poll.votesB; $: percentA = Math.round(poll.votesA / totalVotes) * 100; $: percentB = Math.round(poll.votesB / totalVotes) * 100; console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB); const handleVote = (option, id) => dispatch("vote", {option, id}); </script> <div> <div class = "answer" on:click={() => handleVote("a", poll.id)}{poll.answerA}</div> <div class = "answer" on:click={() => handleVote("b", poll.id)}{poll.answerB}</div> </div> El console.log en el último código da undefined, undefined, undefined, 16, 4 , lo que significa que aunque poll.votesA y poll.votesB llegan al componente, las variables reactivas son undefined . ¿Porqué es eso? ¿Qué hice mal?
En su caso, las variables aún no se han evaluado para registrarlas y la forma de solucionarlo es usar console.log de forma reactiva como la siguiente:
$: totalVotes = poll.votesA + poll.votesB; $: percentA = Math.round(poll.votesA / totalVotes) * 100; $: percentB = Math.round(poll.votesB / totalVotes) * 100; $: console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB);o hazlo todo dentro de un bloque:
let totalVotes, percentA, percentB; $:{ totalVotes = poll.votesA + poll.votesB; percentA = Math.round(poll.votesA / totalVotes) * 100; percentB = Math.round(poll.votesB / totalVotes) * 100; console.log(totalVotes, percentA, percentB, poll.votesA, poll.votesB); }