Quantcast
Channel: Active questions tagged svelte - Stack Overflow
Viewing all articles
Browse latest Browse all 1541

Update component and filter array objects based on month

$
0
0

After a long time I came back to this amazing framework Svelte. I am creating my own calendar that will work with data from a mysql database. I am facing a problem that I cannot solve. My problem is in updating the state of a component where I am trying to filter data from mysql based on the selected month in the calendar. That's why I have to include key code snippets here.

Here is base Calendar.svelte component:

<script>import { onMount } from "svelte";import { fetchData, serverData } from "../server-store";import CalendarDay from "./CalendarDay.svelte";import CoursesTable from "./CoursesTable.svelte";let currentDate = new Date();let currentYear;let currentMonth;let currentMonthString;let daysInMonth;let firstDayOfMonth;let daysInMonthArray;$: {    currentYear = currentDate.getFullYear();    currentMonth = currentDate.getMonth() + 1;    currentMonthString = currentDate.toLocaleString("default", { month: "long" });    daysInMonth = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0).getDate();    firstDayOfMonth = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1).getDay();    daysInMonthArray = Array.from({ length: daysInMonth }, (_, i) => i + 1);}const daysOfWeek = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];const handlePreviousMonth = () => {    currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 1, 1);};const handleNextMonth = () => {    currentDate = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 1);};/** * @param {number} day * @returns {string} date in yyyy-mm-dd format */const getDate = (day) => {    return [String(currentYear), String(currentMonth).padStart(2, "0"), String(day).padStart(2, "0")].join("-");};onMount(() => fetchData())</script><div class="main-container"><div class="mb-4"><h2 class="text-2xl font-semibold">{currentMonthString.toUpperCase()} {currentYear}</h2><div class="flex justify-between mt-2"><input            type="button"            class="btn-switch"            value="Previous month"            on:click={handlePreviousMonth}        /><input            type="button"            class="btn-switch"            value="Next month"            on:click={handleNextMonth}        /></div><div class="calendar-body">        {#each daysOfWeek as day}<div class="font-semibold text-center">{day}</div>        {/each}        {#each Array.from( { length: firstDayOfMonth === 0 ? 6 : firstDayOfMonth - 1 }, ) as _, index (index)}<div class="text-center"></div>        {/each}        {#each daysInMonthArray as day (day)}<CalendarDay date={getDate(day)} serverData={$serverData} />        {/each}</div><CoursesTable data={$serverData} monthIndex={currentMonth} /></div>

And here is second CoursesTable.svelte:

<script>import TableRow from "./TableRow.svelte";export let data = [];export let monthIndex = 0;let sortedData = [];let filteredByMonth = [];$: {    if (data.length > 0) {        const sorted = data.slice().sort((a, b) => {            const dateA = new Date(a.course_date);            const dateB = new Date(b.course_date);            return dateA.getTime() - dateB.getTime();        });        sortedData = [...sorted];    }    filteredByMonth = sortedData.filter(item => {        const _date = new Date(item.course_date);        return _date.getMonth() + 1 === monthIndex;    });}</script><div class="container mx-auto mt-10 p-4 bg-gray-200"><table class="min-w-full bg-white border border-gray-300"><thead><tr class="bg-gray-100"><th class="border px-4 py-2">Vybrané datum</th><th class="border px-4 py-2">Akce</th></tr></thead><tbody>            {#if filteredByMonth.length > 0}                {#each filteredByMonth as data, index}<TableRow index={index} date={data.course_date} classIndex={data.is_close} />                {/each}            {/if}</tbody></table><div class="mt-4"><input type="button" class="bg-blue-500 hover:bg-blue-600 text-white px-4 py-2 rounded" value="Submit" /></div></div>

My goal is for the CoursesTable.svelte component to update when scrolling through the calendar between months so that the component only displays data related to the currently set calendar month.This my current code filters the data. But when the months in the calendar are changed, the CoursesTable.svelte component is updated incorrectly, and it also displays data that is not related to the currently set month at all.

Can someone tell me what I'm doing wrong?


Viewing all articles
Browse latest Browse all 1541

Trending Articles