BlackMath
BlackMath

Reputation: 992

Reactive variables are not working - svelte

Reactive variables are not working in my svelte application. When I log them on my console they are undefined.

I have in App.svelte the following relevant code

<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}/>

In PollsList.svelte I have the following relevant code

<script>
  export let polls = [];
</script>

{#each polls as poll (poll.id)}
  <PollItem {poll} on:vote/>
{/each}

and in my PollItem.svelte I have the following relevant code

<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>

The console.log in the last code gives undefined, undefined, undefined, 16, 4, which means although poll.votesA and poll.votesB reach the component, the reactive variables are undefined. Why is that? What did I do wrong?

Upvotes: 2

Views: 513

Answers (1)

Sherif Salah
Sherif Salah

Reputation: 2143

In your case the variables are not done evaluated yet to log them and the way to fix that is be usning console.log reactively like the following:

$: 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);

or make it all inside a block:

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);
}

Upvotes: 3

Related Questions