I'm trying to render msg from all_msgs array.
<script>
import { sender_msgs } from "../var_store";
import { receiver_msgs } from "../var_store";
const all_msgs = [1,2,3,4];
// $: msgs = all_msgs;
sender_msgs.subscribe((e) => {
all_msgs.push(`Sender: ${e.slice(-1)[0]}`);
});
receiver_msgs.subscribe((e) => {
all_msgs.push(`Receiver: ${e.slice(-1)[0]}`);
console.log(all_msgs);
});
</script>
<div class="chat-window">
{#each all_msgs as msg}
<div>{msg}</div>
{/each}
</div>
<style>
.chat-window {
width: 500px;
border: 1px solid #000;
}
</style>
I can see the numbers can be rendered as html text. But couldn't render other texts when all_msgs is updated by the two subscribe methods. I can see all_msgs in the console having the texts but can't be seen in html. The o/p of the screen and console.log of all_msgs is also shared.
Solved it: reactivity is assignment based. Below code works:
<script>
import { sender_msgs } from "../var_store";
import { receiver_msgs } from "../var_store";
let all_msgs = [];
// $: msgs = all_msgs;
sender_msgs.subscribe((e) => {
all_msgs.push(`Sender: ${e.slice(-1)[0]}`);
all_msgs = all_msgs;
});
receiver_msgs.subscribe((e) => {
all_msgs.push(`Receiver: ${e.slice(-1)[0]}`);
all_msgs = all_msgs;
});
</script>
<div class="chat-window">
{#each all_msgs as msg}
<div>{msg}</div>
{/each}
</div>
<style>
.chat-window {
width: 500px;
border: 1px solid #000;
}
</style>