How to get the points all over the walking path using API Google MAP

I am working on a project where I need to obtain all the coordinate points along a walking route between two specified addresses (source and destination) using the Google Maps API. When using the Google Maps website in walking mode, a blue circle marks the walking path, as illustrated in the image below. I am looking for the function that can replicate this via the API.

Could someone guide me on which function or method in the Google Maps API can be used to achieve this? Any example code or references to the relevant API documentation would be really appreciated.

enter image description here

I have implemented this code, but is not possible to get the same result.

<script>
    let map;
    let directionsService;
    let directionsRenderer;

    function initMap() {
        // Inicializa o mapa
        map = new google.maps.Map(document.getElementById("map"), {
            center: { lat: -23.086325716360644, lng: -47.23343424756318 }, // Coordenadas de São Paulo
            zoom: 15,
        });

        // Cria os serviços do Google Maps
        directionsService = new google.maps.DirectionsService();
        directionsRenderer = new google.maps.DirectionsRenderer();

        // Configura o directionsRenderer para usar o mapa criado
        directionsRenderer.setMap(map);

        // Chama a função para calcular a rota
        calculateAndDisplayRoute();
    }

    function calculateAndDisplayRoute() {
        directionsService.route({
            origin: { lat: -23.088191066799215, lng: -47.24902903973025 },  // Ponto de partida
            destination: { lat: -23.086296107502847, lng: -47.228423881389276 },  // Ponto de chegada
            travelMode: google.maps.TravelMode.WALKING,
        }, (response, status) => {
            if (status === 'OK') {
                directionsRenderer.setDirections(response);
                placeIntermediateMarkers(response);
            } else {
                window.alert('Falha ao calcular a rota: ' + status);
            }
        });
    }

    function placeIntermediateMarkers(directionsResult) {
        const route = directionsResult.routes[0];
        const stepDistance = 5; // Distância desejada entre os pontos, em metros
        let distanceAccumulated = 0;
        let lastPosition = route.overview_path[0]; // Inicialmente, o último ponto é o ponto de origem

        // Criar um marcador no início
        new google.maps.Marker({
            position: lastPosition,
            map: map,
            title: `Start - ${lastPosition.toString()}`
        });

        console.log(lastPosition.toString())
            
        // Iterar sobre os pontos da rota para criar marcadores a cada 40 metros
        route.overview_path.forEach((currentPosition, index) => {
            if (index === 0) {
                return; // Pula o primeiro ponto, já que é o ponto de origem
            }
            console.log(currentPosition.toString())
                
            const segmentDistance = google.maps.geometry.spherical.computeDistanceBetween(lastPosition, currentPosition);
            distanceAccumulated += segmentDistance;
        
            while (distanceAccumulated >= stepDistance) {
                const excessDistance = distanceAccumulated - stepDistance;
                const moveBackDistance = segmentDistance - excessDistance;

                // Calcular a posição proporcional do marcador ao longo do segmento atual
                const intermediatePosition = google.maps.geometry.spherical.interpolate(lastPosition, currentPosition, moveBackDistance / segmentDistance);

                // Criar marcador
                new google.maps.Marker({
                    position: intermediatePosition,
                    map: map,
                    title: `${intermediatePosition.toString()} ${Math.round((stepDistance - excessDistance) + (stepDistance * Math.floor(distanceAccumulated / stepDistance)))}m`
                });

                // Atualizar lastPosition para a posição do último marcador e ajustar o acumulado
                lastPosition = intermediatePosition;
                distanceAccumulated = excessDistance;
            }
        });

        // Criar um marcador no fim
        new google.maps.Marker({
            position: route.overview_path[route.overview_path.length - 1],
            map: map,
            title: `End - ${route.overview_path[route.overview_path.length - 1].toString()}`
        });
    }

</script>

[enter image description here](https://i.sstatic.net/Z4eQNoRm.png)

How can I order an dictionary array by key value? [duplicate]

I have an array with contains multiple dictinary objects. Each objects represents a user and contains a name key. I want the object alphabetically sorted in the array by the value of the name key.

Here a visual representation of what I want to end up with:

// We start with this
[
    {
        name: "foo",
        age: "24"
       },
    {
        name: "bar",
        age: "56"
    }
]

// We end up with this
[
    {
        name: "bar",
        age: "56"
    },
    {
        name: "foo",
        age: "24"
    }
]

Issue in wowonder script [closed]

I was unable to purchase Wonder Script, so I asked a friend to send me the source code so I could test it. When he sent it to me, I noticed that there was a problem with the home page; the css was not displaying, only the html structure. I attempted to fix the problem, but all I could find were the php codes. When I asked my friend if he had touched the code after purchasing it, he replied that he had actually bought it from someone.

I will show you the folder organization and homepage layout down below.

I would appreciate your help if you have ever faced a problem similar to this and have managed to resolve it, or if you are familiar with the Wonder script, Please help me. I am grateful.

enter image description here

With the exception of the homepage, all the other pages function properly. I attempted to solve it using all of my coding knowledge, but I was unable to do so.

vertical Gradient color for each bar is not working in a Grouped Bar Graph which has negative and positive bars using ChartJS

I am using Chart.js grouped bar chart. I want to show my bars with gradient colors. Grouped Bar Currently it show as shown in below image. Any help will be greatly appreciated.

How to create a vertical grouped Bar chart(negative & positve bars) with vertical gradient from top to bottom of each bar bases on its height?

enter image description here

I found a very close solution here, but it sets the createLinearGradient for the whole graph, not for individual bars.

    import { Chart, Chart as ChartJS, registerables } from "chart.js";
import {
    getAxesTitle,
    getGridConfig,
    getLegendsConfig,
    getTooltipConfig,
    getZoomPanConfig,
    numDifferentiation
} from "./ChartJsConfig";
import React, { useEffect, useRef } from "react";

import annotationPlugin from "chartjs-plugin-annotation";
import { BarChartProps } from "types/Interfaces";
import { styleVariable } from "utils/UtilityFunc";
import zoomPlugin from "chartjs-plugin-zoom";

ChartJS.register(
    zoomPlugin,
    annotationPlugin,
    ...registerables
);

const BarChart = (props: BarChartProps) => {

    const { isShowGrid, isShowLegends, isShowTooltip, isZoomPan,
        isStacked, dataSet, zoomConfig, panConfig, annotation, titleInfo } = props;

    const chartContainer = useRef(null);

    function getScales() {
        return {
            x: {
                stacked: isStacked,
                ticks: {
                    color: styleVariable("--chart-scale"),
                    font: {
                        size: 11,
                        weight: "normal",
                        family: "NxtOption-Medium"
                    },
                    "callback": function (value: string | number) {
                        const newThis = this as any;
                        return newThis.getLabelForValue(value);
                    }
                },
                border: {
                    color: styleVariable("--chart-scale"),
                },
                title: getAxesTitle(titleInfo.x),
                grid: getGridConfig(isShowGrid)
            },
            y: {
                stacked: isStacked,
                ticks: {
                    color: styleVariable("--chart-scale"),
                    font: {
                        size: 11,
                        weight: "normal",
                        family: "NxtOption-Medium"
                    },
                    "callback": function (label: number) {
                        return numDifferentiation(label);
                    }
                },
                border: {
                    color: styleVariable("--chart-scale"),
                },
                title: getAxesTitle(titleInfo.y),
                grid: getGridConfig(isShowGrid)
            }
        };
    }

    function updateGradientColors(ctx: any, chartArea: any) {
        
        const redGradient = ctx && ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
        if (redGradient) {
            redGradient.addColorStop(0.2, styleVariable("--bar-chart-red-top-color"));
            redGradient.addColorStop(1, styleVariable("--bar-chart-red-bottom-color"));
        }

        const greenGradient = ctx && ctx.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
        if (greenGradient) {
            greenGradient.addColorStop(0.2, styleVariable("--bar-chart-green-top-color"));
            greenGradient.addColorStop(1, styleVariable("--bar-chart-green-bottom-color"));
        }

        const gradientColors = [
            redGradient, greenGradient
        ];

        return gradientColors;
    }

    function getGradientColors() {
        if (chartContainer && chartContainer.current) {
            const normalColors = [
                styleVariable("--chart-call-oi-area-color"), 
                styleVariable("--chart-put-oi-area-color")
            ];
            
            return dataSet.datasets.map((dataset, idx) => {
                return {
                    ...dataset,
                    backgroundColor: function(context: any) {
                        const chart = context.chart;
                        const { ctx, chartArea } = chart;
                        if (!chartArea) return null;
                        const colors = updateGradientColors(ctx, chartArea);
                        if (colors.length)
                            return colors[ idx ];

                        return normalColors[ idx ];
                    }
                };
            });
        }

        return {};
    }

    useEffect(() => {
        if (chartContainer && chartContainer.current) {
            const configData = {
                type: "bar",
                "data": { ...dataSet, datasets: getGradientColors() },
                options: {
                    responsive: true,
                    animation: false,
                    maintainAspectRatio: false,
                    interaction: {
                        mode: "index",
                    },
                    scales: getScales(),
                    plugins: {
                        legend: getLegendsConfig(isShowLegends),
                        zoom: getZoomPanConfig(isZoomPan, zoomConfig, panConfig),
                        tooltip: getTooltipConfig(isShowTooltip),
                        annotation: annotation ?? ""
                    },
                    layout: {
                        autoPadding: false,
                        padding: {
                            top: 50, 
                            bottom: 10,
                            left: 20,
                            right: 20
                        },
                    }
                }
                
            };
              
            const newChartInstance = new Chart(
                chartContainer.current,
                configData as any
            );
            
            return () => {
                newChartInstance.destroy();
            };
        }

        return () => {
            return "";
        };
    }, [
        chartContainer, dataSet
    ]);

    return (
        <div className="chartjs-container">
            <canvas ref={chartContainer} className="canvas-tag" />
        </div>
    );
};

export default BarChart;

Thanks in Advance.

Warning: validateDOMNesting(…): cannot appear as a child of warning while using Accordion inside tbody

I am using Accordian from react-bootstrap, I want that the table row can be expanded to view another table, it is working fine but giving me warnings on browser console.

<div className="row me-2 ms-2">
                <table className="table accordian-table table header-fixed border mt-2">
                    <thead>
                        <tr>
                            <th width="30%" className="text-center">Col 1</th>
                            <th width="30%" className="text-center">Col 2</th>
                            <th width="30%" className="text-center">Col 3</th>
                            <th width="25px" className="float end"></th>
                        </tr>
                    </thead>
                    <tbody className="scroll">
                        <Accordion activeKey={activeAccordionKey}
                            onSelect={(selectedKey) => setActiveAccordionKey(selectedKey)} flush>
                            {
                                (items?.length) ?
                                    [...items].map((item, index) => {
                                        return (
                                            <tr key={index} onClick={() => getFlows(item)}>
                                                <Accordion.Item eventKey={index}>
                                                    <Accordion.Header className="main-table-content">
                                                        <td width="30%" title={item.prop1} className="text-center pt-2">
                                                            {item.prop1}
                                                        </td>
                                                        <td width="30%" title={item.prop2} className="text-center pt-2">
                                                            {item.onboardingInfo.prop2}
                                                        </td>
                                                        <td width="30%" title={item.prop3} className="text-center pt-2">
                                                            {item.onboardingInfo.prop3}
                                                        </td>
                                                        <td width="25px">{" "}</td>
                                                    </Accordion.Header>
                                                    <Accordion.Body>
                                                        <table className="table" onClick={(e) => e.stopPropagation()}>
                                                            <thead>
                                                                <tr>
                                                                    <th>Flow Name</th>
                                                                    <th>Flow Type</th>
                                                                    <th>Dnid</th>
                                                                    <th>Ext</th>
                                                                    <th>Created By</th>
                                                                    <th>Created On</th>
                                                                </tr>
                                                            </thead>
                                                            <tbody>
                                                                {
                                                                    (selectedItem?.length) ?
                                                                        [...selectedItem.values()].map((slItem) => {
                                                                            return (
                                                                                <tr key={slItem.flowName}>
                                                                                    <td>{slItem.flowName}</td>
                                                                                    <td>{slItem.flowTypeId}</td>
                                                                                    <td>{slItem.dnid}</td>                                                                                        
                                                                                    <td>{slItem.createdBy}</td>
                                                                                    <td>{slItem.createdOn}</td>
                                                                                </tr>
                                                                            )
                                                                        })
                                                                        : <tr><td>No Configs Available</td></tr>
                                                                }
                                                            </tbody>
                                                        </table>
                                                    </Accordion.Body>
                                                </Accordion.Item >
                                            </tr>
                                        )
                                    }) : <tr><td>No ItemsFound</td></tr>
                            }
                        </Accordion>
                    </tbody>
                </table>
            </div>

It gives me following warning in browser console:
Warning: validateDOMNesting(…): cannot appear as a child of .

Can someone please help me removing this, or any other alternative?

Struggling to set Lottie stage when DOM loads

I’m facing a challenge with dynamically setting the stage of a Lottie upon the DOM content being fully loaded. My goal is to randomly select a Lottie and a specific stage in it, and then display the animation starting from the selected stage. However, despite my efforts, the animation does not start from any stage. Any insights into resolving this issue would be greatly appreciated.

Here is my code:

document.addEventListener("DOMContentLoaded", function () {
    // List of the Lotties
    var lottieFiles = [
        {
            path: 'lottie1.json',
            stages: [
                { from: 0, to: 50 },
                { from: 51, to: 100 },
                { from: 101, to: 150 },
                { from: 151, to: 200 }
            ]
        },
        {
            path: 'lottie2.json',
            stages: [
                { from: 0, to: 60 },
                { from: 61, to: 120 },
                { from: 121, to: 180 },
                { from: 181, to: 240 }
            ]
        },
        {
            path: 'lottie3.json',
            stages: [
                { from: 0, to: 40 },
                { from: 41, to: 80 },
                { from: 81, to: 120 },
                { from: 121, to: 160 }
            ]
        },
        {
            path: 'lottie4.json',
            stages: [
                { from: 0, to: 70 },
                { from: 71, to: 140 },
                { from: 141, to: 210 },
                { from: 211, to: 280 }
            ]
        }
    ];

    // Choose random Lottie
    var randomIndex = Math.floor(Math.random() * lottieFiles.length);
    var selectedLottie = lottieFiles[randomIndex];

    // Choose random stage
    var randomStageIndex = Math.floor(Math.random() * selectedLottie.stages.length);
    var selectedStage = selectedLottie.stages[randomStageIndex];

    // Load the selected Lottie from it's stage
    var animation = lottie.loadAnimation({
        container: document.getElementById('lottie-animation'),
        renderer: 'svg',
        loop: true,
        autoplay: true,
        path: selectedLottie.path
    });

    animation.goToAndStop(randomStageIndex.from, true);
});

I was trying to solve the issue by refining the stage selection logic. I revisited the script and adjusted how it identifies and sets the animation stage. Specifically, I made changes to directly specify the stage for the animation without relying on a random index. However, it still shows up at the wrong stage.

filtering an object-array based on another object-array (orderly)

here is my data:

arrayA= [{"studentID":1,"Type":"A"},{"studentID":2,"Type":"B"},{"studentID":3,"Type":"C"},{"studentID":4,"Type":"A"}]
filteredArrayOrderlyOn = [{"studentID":1},{"Type":"A"}] (depending on the order the user selects the filters)

Output should be 
arrayA = [{"studentID":1,"Type":"A"}]

or if the filteredArrayOrderlyOn array changes because user has control on this selection.

filteredArrayOrderlyOn  = [{"Type":"B"},{"studentID":1}] then output should be nothing []

So i would like to filter ArrayA, in the correct order, meaning that in filteredArrayOrderly first the filter should be studentID=1 and then Type which is A.

i have been trying without any luck


newArray = arrayA.filter(function (item) {
    return Object.keys(elem) === Object.keys(item);
  });
})

or using lodash

 newArray = _.filter(arrayA, function (elem) {
  //     return elem.Type=== filteredArrayOrderlyOn.Type ||  elem.studentID=== filteredArrayOrderlyOn.studentID
  //   });

but getting too many repetitions
thakns guys

“Error: crypto.getRandomValues must be defined” on React Native Expo using @Solana/Web3.js

Im building a solwallet using Solana/Web3/js, and i need to create a wallet account, so my approach is generate mnemonic so it can become seeds for a keypair, so it’ll be the recovery phrase if needed.

heres my approach code

export default async function generateKeypair() {
  const mnemonic = bip39.generateMnemonic();

  // Convert mnemonic to binary seed
  const seedBytes = await mnemonicToSeed(mnemonic);

  const keypair = Keypair.fromSeed(seedBytes);

  const privateKey = keypair.secretKey;
  const publicKey = keypair.publicKey;

  // Convert the private key to a base58 string
  const base58PrivateKey = bs58.encode(privateKey);

  // Convert into Hex string
  const privateKeyHex = Array.from(privateKey)
    .map((byte) => byte.toString(16).padStart(2, '0'))
    .join('');

  return { base58PrivateKey, privateKeyHex, publicKey, mnemonic };
}

But i got an error which from node_modules/react-native
it says

Error creating wallet: [Error: crypto.getRandomValues must be defined]

when I debug it one by one, the cause is from

const mnemonic = bip39.generateMnemonic();

anyway i call it like this

export default function createWallet() {
  const handleCreateWallet = async () => {
    try {
      const { mnemonic } = await generateKeypair();

      // console.log(' Base 58 Private Key:', base58PrivateKey);
      // console.log(' Hex Private Key:', privateKeyHex);
      // console.log('Public Key:', publicKey);
      console.log('Mnemonics:', mnemonic);
    } catch (error) {
      console.error('Error creating wallet:', error);
    }
  };
  return (
    <View>
      <Button title="Generate Wallet" onPress={handleCreateWallet} />
    </View>
  );
}

so it got me stuck in here, I cant generate a key pair from mnemonics

ps. im new in this web3 thing, if anyone have different approach or logic so please enlighten me

Getting selected items from NextUI-Table

I’m absolutely new to JS and NextUI. I work with C# and DotNET normally.
I need to build a table with items that are selectable and at the click of a button, all the selected items should get passed to a ‘use server’ function that accepts a JSON-Array.

Now I’m stuck at getting the selected items from the table.

Here is what I tried, following some tutorials:

//...
const [selectedKeys, setSelectedKeys] = React.useState(new Set([]));
    return (
        <section className="flex flex-col items-center justify-center gap-4 py-8 md:py-10">
            <div className="inline-block max-w-lg text-center justify-center">

                <h2 className={subtitle({ class: "mt-4" })}>
                    Bitte die zu entfernenden Rezensionen auswählen:
                </h2>
            </div>

            <div className="flex flex-col gap-3">
                <Table
                    color="primary"
                    selectionMode="multiple"
                    aria-label="Example static collection table"
                    isStriped
                selectedKeys={selectedKeys}
                onSelectionChange={setSelectedKeys}
                >
                    <TableHeader columns={columns}>
                        {(column) => <TableColumn key={column.key}>{column.label}</TableColumn>}
                    </TableHeader>
                    <TableBody items={reviews}>
                        {(item) => (
                            <TableRow key={item.key}>
                                {(columnKey) => <TableCell>{getKeyValue(item, columnKey)}</TableCell>}
                            </TableRow>
                        )}
                    </TableBody>
                </Table>
//...

the item.key is a number as in all the tutorials, even on the NextUI documentation.

In VS-Code it gives me this message on the onSelectionChange method:

Type 'Dispatch<SetStateAction<Set<never>>>' is not assignable to type '(keys: Selection) => void'.
  Types of parameters 'value' and 'keys' are incompatible.
    Type 'Selection' is not assignable to type 'SetStateAction<Set<never>>'.
      Type 'string' is not assignable to type 'SetStateAction<Set<never>>'.ts(2322)
selection.d.ts(39, 3): The expected type comes from property 'onSelectionChange' which is declared here on type 'IntrinsicAttributes & MergeWithAs<Omit<DetailedHTMLProps<TableHTMLAttributes<HTMLTableElement>, HTMLTableElement>, "ref">, Omit<...>, TableProps, "table">'

If I run it, there is this message:

Error Message

It’s pretty frustrating…

Is this code enough to secure eval() from external source? [closed]

Since i am restricting the access to window, this, and document is this safe to run the code, what are the other ways can this code get access to my environment ?

function evaltest(){

    "use strict";

    var window = null;
    var document = null;

    var string = ' "use strict"; ' + 'var test = 123; console.log(document, window)';

    eval(string);

}
evaltest();

The response data variable populated by an AJAX call contains source code rather than the data sent from the server (on MS Edge)

I have the strangest issue! This only happens on MS Edge and only for certain users at a certain client. In summary when an ajax call is made to the server, instead of the response data variable holding the server response it is holding some source code from the platform instead. Code below…I’m not sure how this could be possible ?!? We cannot reproduce ourselves – but we can screen share with the user and confirm the issue

Ajax code:

        console.log("Calling: " + api);
        $.ajax({
            url: api,
            cache: true,
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                displayExceptionNotification("Error on call to " + api + ": " + errorThrown);
            }
        }).then(function (theData) {
// Use the server response
}

The variable ‘theData’ does not hold the JSON data coming back from the server instead it holds the contents of a totally unrelated .js file?!? We know this because we can remote view/share with the user, use the inspect/debug tool and hover over to see the value of ‘theData’ – see attached screenshot. I cannot come up with any reason why this would be – but of course when the follow on code runs instead of getting the expected JSON it’s getting a bunch of raw js source code and failing..

Any ideas?

edge

Apache eCharts – yAxis legend without overlap

With eCharts, I’m trying to find a solution to display the yAxis name properly for every screen size and chart content.
Starting from this example, where the axis name overlaps with the axis labels:

option = {
  xAxis: {
    type: 'category',
    data: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  },
  yAxis: [{
    name: "TEST",
    nameLocation: "middle",
  }],
  series: [
    {
      data: [1500, 2300, 2240, 2180, 1350, 1470, 2600],
      type: 'line',
    }
  ]
};

I tried adding a padding to move the name and make it not overlap.

  yAxis: [
    {
      name: 'TEST',
      nameLocation: 'middle',
      nameTextStyle: {
        padding: [0, 0, 50, 0]
      }
    }
  ],

but that has two problems:

  1. it doesn’t always work if the labels are longer (e.g. if the data has 8 digits instead of 4)
  2. if I reduce slightly the screen size, the name of the axis goes out of bounds.

How can I solve this problem? Is there a way to express the margin in a relative way from the axis labels?

No overload matches this call when I’m trying to call using tanstack query

so I’m trying to call a single data in my database, it was working successfully when I’m using a useEffect hook, but right now, I’m trying to learn tanstack@query. but I got an error when I tried to call it.

No overload matches this call. Overload 1 of 3, ‘(options:
DefinedInitialDataOptions<unknown, Error, unknown, (string |
string[])[]>, queryClient?: QueryClient | undefined):
DefinedUseQueryResult<unknown, Error>’, gave the following error.
Type ‘Promise<{ id: string; title: string; email: string; fullName: string; contactPerson: string; department: string;
dateOfEvent: string; startingTime: string; endingTime: string;
purpose: string; doesHaveDryRun: string; … 11 more …; updatedAt:
Date; } | { …; } | null>’ is not assignable to type ‘unique symbol |
QueryFunction<unknown, (string | string[])[], never> | undefined’.
Overload 2 of 3, ‘(options: UndefinedInitialDataOptions<unknown,
Error, unknown, (string | string[])[]>, queryClient?: QueryClient |
undefined): UseQueryResult<unknown, Error>’, gave the following error.
Type ‘Promise<{ id: string; title: string; email: string; fullName: string; contactPerson: string; department: string;
dateOfEvent: string; startingTime: string; endingTime: string;
purpose: string; doesHaveDryRun: string; … 11 more …; updatedAt:
Date; } | { …; } | null>’ is not assignable to type ‘unique symbol |
QueryFunction<unknown, (string | string[])[], never> | undefined’.
Overload 3 of 3, ‘(options: UseQueryOptions<unknown, Error, unknown,
(string | string[])[]>, queryClient?: QueryClient | undefined):
UseQueryResult<unknown, Error>’, gave the following error.
Type ‘Promise<{ id: string; title: string; email: string; fullName: string; contactPerson: string; department: string;
dateOfEvent: string; startingTime: string; endingTime: string;
purpose: string; doesHaveDryRun: string; … 11 more …; updatedAt:
Date; } | { …; } | null>’ is not assignable to type ‘unique symbol |
QueryFunction<unknown, (string | string[])[], never> |
undefined’.ts(2769) types-MRM6XQm8.d.ts(557, 5): The expected type
comes from property ‘queryFn’ which is declared here on type
‘DefinedInitialDataOptions<unknown, Error, unknown, (string |
string[])[]>’ types-MRM6XQm8.d.ts(557, 5): The expected type comes
from property ‘queryFn’ which is declared here on type
‘UndefinedInitialDataOptions<unknown, Error, unknown, (string |
string[])[]>’ types-MRM6XQm8.d.ts(557, 5): The expected type comes
from property ‘queryFn’ which is declared here on type
‘UseQueryOptions<unknown, Error, unknown, (string | string[])[]>’

This is my component


"use client";

import { getDataById } from "@/data-query/appointment";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import React, { useEffect, useState, useTransition } from "react";

export default function EventPageDetail() {

  const {eventId} = useParams()


  const {data, error, isFetching} = useQuery({
    queryKey: ['eventId', eventId],
    queryFn: getDataById(eventId)
  })

  return <div></div>;
}

and this is my server action

export async function getDataById(id: any){
  try {
    const data = await db.appoinmentSchedule.findUnique({
      where: {
        id:id
      }
    })

    return data
  } catch (error) {
    return {error: "Something went wrong"}
  }
}

i want change the locale for a particular component/current component

I’m working on an Angular 17 application where I’ve implemented i18n for internationalization. Initially, I’ve set Arabic as the default language for the entire application. Now, I need to switch to English for specific components based on some condition. Could someone guide me on how to achieve this.
Thank you

  public sidebarShow: boolean = false;
  setLang = 1; // Assuming setLang is set based on some condition

  constructor(@Inject(LOCALE_ID) public locale: string,
  private cdr: ChangeDetectorRef) {
  }

  ngOnInit(): void {
   this.setLocale();
  }
  setLocale(): void {
    if (this.setLang === 1) 
    {
      // Set English locale
      this.locale = 'en-US';
      console.log(this.locale)
    } else {
      // Set Arabic locale
      this.locale = 'ar-SA';
      console.log(this.locale);
    }
    this.cdr.detectChanges(); // Trigger change detection
  }  
<div >
    <div class="bg-primary" > 
        <h1  i18n>Features sections</h1>
        <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
        <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
        <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
    </div>
</div>

<div> 
    <h1 i18n>Blogs sections</h1>
    <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
    <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
    <p i18n>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Tempora excepturi, ducimus repudiandae aspernatur molestias accusantium debitis iusto praesentium voluptate error mollitia pariatur fugit qui ut deserunt quod rem magnam hic!</p>
</div>