What is the reason my Barchart begins on day 2 rather than day 1?

I have a concern regarding the data retrieval process using tanstackquery. Currently, I am facing an issue where the day starts at day 2 instead of day when I attempt to display the data.

https://i.sstatic.net/LRTQztFd.png

This is how I retrieve my data from the server.

api/result-overview.tsx

export async function GET(request: Request) {
const { searchParams } = new URL(request.url)
  const timeframe = searchParams.get('timeframe')
  const year = searchParams.get("year")
  const month = searchParams.get("month")


  const queryParams = getHistoryDataSchema.safeParse({
    timeframe,
    year,
    month
  })


  if (!queryParams.success) {
    return Response.json(queryParams.error.message, {
      status: 400
    })
  }


  try {
    const data = await getHistoryData(
      queryParams.data.timeframe, {
      month: queryParams.data.month,
      year: queryParams.data.year
    })


    return Response.json(data)
  } catch (error) {

    return Response.json(error)
  }

}


async function getMonthHistoryData(year: number, month: number): Promise<HistoryData[]> {
  const statuses = ['pending', 'approved', 'done', 'cancel'] as const;
  type Status = typeof statuses[number];

  const results = await Promise.all(
    statuses.map(status =>
      db.scheduleDate.groupBy({
        by: ['day'],
        where: {
          year,
          month,
          soft_delete_scheduleDate: false,
          appointment: {
            soft_delete: false,
            status
          }
        },
        orderBy: [{ day: 'asc' }],
        _count: { _all: true },
      })
    )
  );

  const daysInMonth = new Date(year, month + 1, 0).getDate();

  const history: HistoryData[] = Array.from({ length: daysInMonth }, (_, i) => {
    const day = i + 1;
    const counts: StatusCounts = {
      pending: 0,
      approved: 0,
      done: 0,
      cancel: 0,
    };

    statuses.forEach((status, index) => {
      const dayData = results[index].find(item => item.day === day);
      counts[status] = dayData ? dayData._count._all : 0;
    });

    return { year, month, day, counts };
  });

  return history;
}

And then, I implement it in my front-end using tanstack query. To create a smooth transition before displaying the actual code, I created a skeleton. However, I believe there is an issue along this line.

const date = new Date(year, month, (day ? day + 1 : 1));

History.tsx

  const historyDataQuery = useQuery({
    queryKey: ['overview', 'history', timeFrame, period],
    queryFn: () => fetch(`/api/result-overview?timeframe=${timeFrame}&year=${period.year}&month=${period.month}`)
      .then((res) => res.json())
      .then((data) => data.map((item: any) => ({
        ...item,
        pending: item.counts.pending,
        approved: item.counts.approved,
        done: item.counts.done,
        cancel: item.counts.cancel,

      })))
  });


return (
<SkeletonWrapper isLoading={historyDataQuery.isFetching}>
              {dataAvailable && (
                <ResponsiveContainer width={"100%"} height={300}>
                  <BarChart data={historyDataQuery.data}>
                    <XAxis
                      stroke="#888888"
                      fontSize={12}
                      tickLine={false}
                      axisLine={false}
                      padding={{ left: 5, right: 5 }}
                      dataKey={(data) => {
                        const { year, month, day } = data;
                        const date = new Date(year, month, (day ? day + 1 : 1));
                        if (timeFrame === "year") {
                          return date.toLocaleDateString("default", {
                            month: "short",
                          });
                        }
                        return date.toLocaleDateString("default", {
                          day: "2-digit",
                        });
                      }}
                    />
                    <YAxis
                      stroke="#888888"
                      fontSize={12}
                      domain={[0, 10]}
                      tickLine={false}
                      axisLine={false}
                    />
                    <Bar dataKey="pending" fill="#eab308" />
                    <Bar dataKey="approved" fill="#10b981" />
                    <Bar dataKey="done" fill="#3b82f6" />
                    <Bar dataKey="cancel" fill="#ef4444" />

                    <Tooltip
                      cursor={{ opacity: 0.1 }}
                      content={(props) => (
                        <CustomToolTip {...props} />
                      )}
                    />
                  </BarChart>


                </ResponsiveContainer>
              )}
            </SkeletonWrapper>
)

However, changing it to

const date = new Date(year, month, day || 0);

causes the data to shift from 12 to 11

https://i.sstatic.net/H3PbwqLO.png

Answer №1

Chances are, the main reason is having a 1-based day already present in your code.

const historyData: HistoryData[] = Array.from({ length: daysInMonth }, (_, index) => {
    const currentDay = index + 1;

Then, you inadvertently increase it once more like this:

const { year, month, day } = userData;
const newDate = new Date(year, month, (day ? day + 1 : 1));

Before creating the date object, consider logging the day variable from the second fragment.

Answer №2

To eliminate the gap, simply set the interval to 0.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Verify characteristics of recursive object within Angular 7

I have an object similar to the one in the stackblitz linked below and I need to determine if a key is of type Date. If it is, I want to add 3 days to that date. I have successfully implemented this for non-recursive objects, but I am facing challenges wit ...

Comparing strings in TypeScript

After extensively studying string equality in JavaScript, I naturally assumed the same rules would apply in TypeScript. However, I am encountering a perplexing issue. I have two identical strings that do not produce equal results when using the == and === ...

Utilizing Type Script 1.8 with Visual Studio 2017 for older projects: A step-by-step guide

After installing Visual Studio 2017, I encountered a TypeScript error when trying to run my project. It seems that VS 2017 is using TypeScript 2.1.5, while my application was designed for TypeScript 1.8. Is there a way to make VS 17 utilize TypeScript 1.8 ...

Tips for integrating React with Cloudinary using Typescript

I'm currently immersed in a TypeScript and React project. Attempting to implement react cloudinary for image uploading and URL retrieval. Encountering errors when trying to convert the provided JavaScript code to TypeScript (tsx). The sample code I w ...

What is the best way to merge three arrays of data into a single iterable array?

I am working on a function that fetches data from an API. In this process, I execute a total of 3 queries, each returning an array of data. My goal is to combine these 3 arrays into a single iterable array, where the indexes correspond to the original a ...

Tips for Incorporating Material Design Lite into Angular2

I have encountered a minor issue while trying to incorporate material design into Angular2. I am using the latest version of Angular2, but the MDL framework seems to be incompatible. Here is what I have done so far: npm install material-design-lite --sav ...

React: The useContext hook does not accurately reflect the current state

I'm currently facing a dilemma as I attempt to unify data in my app. Whenever I click the button, the isDisplay value is supposed to be set to true; even though the state changes in my context file, it does not reflect in the app. Thank you for your ...

Ways to retrieve interface definition using a variable

I have an interface that organizes various states together export interface ScanFiltersStatePage1 { keywords: SensitiveInfoFileKeywordFilter categories: string[] classifications: string[] fileTypes: string[] infotypes: string[] regulations: str ...

Steps to automatically close a modal in Angular 7 after selecting a link within the modal

I have a modal with a link that opens another page when clicked. However, the modal does not close when the link opens a new page. Can you help me figure out how to close the modal? × Important Note We strongly advise making individual reservatio ...

Error: Unable to instantiate NGXLoggerHttpService due to an issue with the HttpBackend injection in the AppModule

I encountered an error message after updating my NgxLogger module: main.ts:17 NullInjectorError: StaticInjectorError(AppModule)[NGXLoggerHttpService -> HttpBackend]: StaticInjectorError(Platform: core)[NGXLoggerHttpService -> HttpBackend]: N ...

Fire the props.onChange() function when the TextField component is blurred

Currently, I am in the process of developing a NumberField component that has unique functionality. This component is designed to remove the default 0 value when clicked on (onFocus), allowing users to input a number into an empty field. Upon clicking out ...

Suggesting prop names for styled-components using TypeScript

Can anyone help me with styled-components to show suggestion props name? I've created a styled component called CardHeader and added props. interface ICardHeader { darkMode?:boolean } https://i.sstatic.net/eDlOv.png https://i.sstatic.net/urxvK.png ...

Splitting an array of objects into multiple arrays of objects based on their properties

At the moment, I am working with an array that contains multiple objects const bankData = [ { "bank": "Chase", "monthEndBalance": "72,175.88", "bankStatementDate": "2020/10/31&quo ...

Executing vitest on compiled javascript files

Currently facing issues running vitest on compiled JavaScript. Numerous errors are appearing, such as: TypeError: Cannot read properties of undefined (reading 'spyOn') TypeError: Cannot read properties of undefined (reading 'mock') and ...

Assign a default value to empty elements in an array

Here is an example of fetching data in an array: [ { "Id": 111, "Name": "Test 1", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de8e0ece4e1bccde9e2e0ece4e3a3e3e8f9">[email protect ...

Leverage the power of Maps in TypeScript by incorporating additional fields

There is a slight issue I am facing. The data I have looks like this: ["1112234", "S1044N", "A1041DS"] I am interested in using Map to generate a new array, but I wish to include additional properties for each field. Here is ...

Typescript Jest testing reveals inaccurate error line information

While running a sample Jest test on a particular structure, I noticed that the errors in the output summary from Jest are not lining up correctly. Here is a snippet from my package.json file: "devDependencies": { "@types/jest": "^22.0.1", "jest": ...

Angular Pagination Showing Incorrect Page Count as "1-10 of 10" After Moving to Next Page Even with Accurate Total Item Count

Encountering an issue with Angular Material's MatPaginator where it shows "1-10 of 10" after moving to the second page, despite receiving correct total item count from the API. Pagination functions correctly on the initial page, but fails to update up ...

What sets Babel and TypeScript apart from each other in terms of functionality and features?

While TypeScript was utilized to create Angular2, Babel also appears quite similar. Many established companies prefer Babel over TypeScript. Here are some questions to consider: What specific advantages does each one offer? Which is a better or worse ch ...

Tips for dynamically importing parent services

Is it possible to dynamically import service-A (85KB) into service-B (15KB) and then dynamically import service-B into app.comp.ts when needed? Check out the Stackblitz Demo here View the FlowChart here ...