Hiding tooltip color box in Chart.js not working

As per Chart.js docs, all that’s needed to remove the color box from tooltips is to add displayColors: false to tooltip, that’s also the accepted answer to a similar question here How to remove square label from tooltip and make its information in one line?
But it doesn’t work in my code. Here’s the link to the editor https://stackblitz.com/edit/stackblitz-starters-ntdk3g?file=src%2FApp.js

a-frame displaying a Black Screen instead of my 360 Panorama Image

I am using the a-frame CDS found at the following link to display my 360 panorama image, which I have included in my index.html file as follows:

<script src="https://cdnjs.cloudflare.com/ajax/libs/aframe/1.4.2/aframe.min.js" integrity="sha512-XXX==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>

I have then added the following code to my homepage Vue.js Component. I have confirmed that the path to the image is accurate.

  <body>
    <div class="body-image">
      <a-scene>
        <a-sky src="../assets/Images/HomePage.jpg"></a-sky>
      </a-scene>
    </div>
  </body>

However, I am obtaining a black screen instead of the image and the following error: HEAD 404 (Not Found) src-loader.js:120 (anonymous)

What am I doing wrong?

Updated/increment the existing value when a new orderId is pushed in Javascript

here is the array with the objects, and when i push a new object with order 2, i would like to increment the noOfSubmit whenever a new orderId is pushed , is there a way to achieve the following using javascript?

Input array

[{"orderId":1,"noOfSubmit":1,"orderNo":"A"},
{"orderId":1,"noOfSubmit":1,"orderNo":"B"},
{"orderId":1,"noOfSubmit":1,"orderNo":"C"},
{"orderId":1,"noOfSubmit":1,"orderNo":"D"}]

{"orderId":2,"noOfSubmit":1,"orderNo":"E"} – Push this to the array above

Expected output:

[{"orderId":1,"noOfSubmit":2,"orderNo":"A"},
{"orderId":1,"noOfSubmit":2,"orderNo":"B"},
{"orderId":1,"noOfSubmit":2,"orderNo":"C"},
{"orderId":1,"noOfSubmit":2,"orderNo":"D"},
{"orderId":2,"noOfSubmit":1,"orderNo":"E"}]

{"orderId":2,"noOfSubmit":1,"orderNo":"F"} – Push this next to the same array above

Expected output:

[{"orderId":1,"noOfSubmit":2,"orderNo":"A"},
{"orderId":1,"noOfSubmit":2,"orderNo":"B"},
{"orderId":1,"noOfSubmit":2,"orderNo":"C"},
{"orderId":1,"noOfSubmit":2,"orderNo":"D"},
{"orderId":2,"noOfSubmit":1,"orderNo":"E"},
{"orderId":2,"noOfSubmit":1,"orderNo":"F"}]

{"orderId":3,"noOfSubmit":1, "orderNo":"G"} –> now push this object

Expected output:

[{"orderId":1,"noOfSubmit":3,"orderNo":"A"},
{"orderId":1,"noOfSubmit":3,"orderNo":"B"},
{"orderId":1,"noOfSubmit":3,"orderNo":"C"},
{"orderId":1,"noOfSubmit":3,"orderNo":"D"},
{"orderId":2,"noOfSubmit":2,"orderNo":"E"},
{"orderId":2,"noOfSubmit":2,"orderNo":"F"},
{"orderId":3,"noOfSubmit":1,"orderNo":"G"} ]

{"orderId":3,"noOfSubmit":1, "orderNo":"H"} –> now push this object

Expected output:

[{"orderId":1,"noOfSubmit":3,"orderNo":"A"},
{"orderId":1,"noOfSubmit":3,"orderNo":"B"},
{"orderId":1,"noOfSubmit":3,"orderNo":"C"},
{"orderId":1,"noOfSubmit":3,"orderNo":"D"},
{"orderId":2,"noOfSubmit":2,"orderNo":"E"},
{"orderId":2,"noOfSubmit":2,"orderNo":"F"},
{"orderId":3,"noOfSubmit":1, "orderNo":"G"},
{"orderId":3,"noOfSubmit":1, "orderNo":"H"} ]

How fix this error Warning: Prop `data-rbd-draggable-context-id` did not match. Server: “7” Client: “0”

My Code:

Server side works fine.

Error terminal image
Error terminal image

There are error messages here. I tried many variants but could not find a solution. I need creative solutions. Sometimes when I look at the code too much, I can’t see the errors. Chatgpt also fell short in this regard.

Note: I have to deliver the project within 3 days. So I request you please take a look at my code

import React, { useState, useEffect, useRef } from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

const DragAndDropExample = () => {
  const [data, setData] = useState([]);
  const droppableRef = useRef(null);
  const [newTodo , setNewTodo] = useState("")

  const CreateTodo = ()=>{
    ...
}

  const CompleteTodo = (id) => {
    ...
  };

  const DeleteTodo = (id) => {
    fetch(`http://localhost:1283/todo/delete/${id}`, {
      method: "DELETE",
      headers: {
        "Content-Type": "application/json",
        "Authorization": "Bearer " + localStorage.getItem("jwt")
      }
    })
      .then(res => res.json())
      .then(() => {
        // Eski veriyi güncelle
        setData(prevData => {
          // Silinen öğeyi veri listesinden çıkar
          const updatedData = prevData.filter(item => item._id !== id);
          return updatedData;
        });
      });
  };

  useEffect(() => {
    fetch('http://localhost:1283/mytodo', {
      headers: {
        "Authorization": "Bearer " + localStorage.getItem("jwt")
      }
    })
      .then(res => res.json())
      .then(result => {
        console.log(result.mytodo);
        setData(result.mytodo);
      });
  }, []);

  const handleDragEnd = (result) => {
    if (!result.destination) return;

    // Yer değiştirme işlemini gerçekleştir
    const newItems = Array.from(data);
    const [reorderedItem] = newItems.splice(result.source.index, 1);
    newItems.splice(result.destination.index, 0, reorderedItem);

    // Sıralanmış öğeleri güncelle
    setData(newItems);

    // Yer değiştikten sonra veriyi güncelle
    setData(newItems.map(item => ({
      ...item,
      isCompleted: data.find(d => d._id === item._id).isCompleted
    })));

    // Eğer sürüklenen öğe silindi ise, güncellenmiş veriyi kontrol edin
    if (result.type === 'REORDER' && !newItems.find(item => item._id === result.draggableId)) {
      setData(prevData => prevData.filter(item => item._id !== result.draggableId));
    }
  };


  return (  
    <DragDropContext onDragEnd={handleDragEnd} onBeforeCapture={() => droppableRef.current && droppableRef.current.removeAttribute('data-rbd-draggable-context-id')}>
      <div className='flex flex-col items-center justify-center'>
        <h1 className='mb-4 text-3xl font-semibold'>Todot's</h1>
        <div className='flex items-center py-4 max-w-[300px] mx-4 justify-center'>
          <input className='p-4 bg-white rounded-lg' value={newTodo} onChange={(e) => setNewTodo(e.target.value)} />
          <div className="group" onClick={()=> CreateTodo()}>
            <img src='/icon/plus.svg' alt='' className='group-hover:hidden min-w-6 w-14  mx-2 p-3.5 cursor-pointer' />
            <img src='/icon/plus_white.svg' alt='' className='hidden group-hover:block min-w-6 w-14 mx-2 p-3.5 cursor-pointer bg-[#4942E4] rounded-md' />
          </div>
        </div>
        <Droppable droppableId="droppable" innerRef={droppableRef}>
          {(provided) => (
            <div
              className="bg-slate-200"
              ref={(ref) => {
                provided.innerRef(ref);
                droppableRef.current = ref;
              }}
              {...provided.droppableProps}
            >
              {data.map((item, index) => (
                <Draggable key={item._id} draggableId={item._id} index={index}>
                  {(provided, snapshot) => (
                    <div
                      className='p-1'
                      ref={provided.innerRef}
                      {...provided.draggableProps}
                      {...provided.dragHandleProps}
                      data-rbd-draggable-context-id={undefined} // Özelliği kaldır
                    >
                      <div className='bg-white m-1 py-5 px-4 rounded-md min-w-[300px] flex items-center justify-between cursor-default'>
                        <span className={item && item.isCompleted ? 'line-through' : ''}>{item.toDoText}</span>
                        <div className="flex items-center justify-around">
                          <div className="group" onClick={() => DeleteTodo(item._id)}>
                            <img src='/icon/trash.svg' alt='' className='group-hover:hidden w-8 mx-1 p-1.5 cursor-pointer' />
                            <img src='/icon/trash_white.svg' alt='' className='hidden group-hover:block min-w-4 w-8 mx-1 p-1.5 cursor-pointer bg-red-500 rounded-md' />
                          </div>
                          <div className="group" onClick={() => CompleteTodo(item._id)}>
                            <img src='/icon/check.svg' alt='' className='group-hover:hidden min-w-6 w-8 mx-2 p-1.5 cursor-pointer' />
                            <img src='/icon/check_white.svg' alt='' className='hidden group-hover:block min-w-6 w-8 mx-2 p-1.5 cursor-pointer bg-green-500 rounded-md' />
                          </div>
                        </div>
                      </div>
                    </div>
                  )}
                </Draggable>
              ))}
              {provided.placeholder}
            </div>
          )}
        </Droppable>
      </div>
    </DragDropContext>
  );
};

export default DragAndDropExample

Why onCancel test is failing?

I’ve written two tests; one to test the Download button and the other to test the Cancel button. Why is the Cancel test failing?

Here is the code I am trying to run two simple tests on the Download (handleDownload) and cancel (handleCancel) buttons.

import React from 'react';
import { Button, Modal, ModalFooter } from 'react-bootstrap';
import ReactDOM from 'react-dom';

import Select from 'controls/Select/Select';
import { getModalRoot } from 'sd/components/layout/admin/forms/FvReplaceFormModal/helpers';
import { DOWNLOAD_BUTTON_TEXT, CANCEL_BUTTON_TEXT } from 'sd/constants/ModalWindowConstants';

import 'sd/components/layout/admin/forms/FvReplaceFormModal/style.scss';
import type { SelectOption } from 'shared/types/General';

const { Body: ModalBody, Header: ModalHeader, Title: ModalTitle } = Modal;

export interface ChooseLanguageModalProps {
    languageList: SelectOption[];
    onDownloadLanguage: (value?: string) => void;
    onDownload: () => void;
    onCancel?: () => void;
}

const HEADER_TITLE = 'Choose language page';
const CHOOSE_LANGUAGE_LABEL = 'Choose language';

export const ChooseLanguageModal = (props: ChooseLanguageModalProps) => {
    const { languageList } = props;

    const onChangeLanguage = (value?: string | undefined) => {
        const { onDownloadLanguage } = props;
        onDownloadLanguage(value);
    };

    const handleCancel = async () => {
        await hideChooseLanguageModal();
    };

    const handleDownload = async () => {
        const { onDownload } = props;
        onDownload();

        await hideChooseLanguageModal();
    };

    return (
        <Modal
            show
            backdrop="static"
            animation={false}
            container={getModalRoot()}
            onHide={() => hideChooseLanguageModal()}
        >
            <ModalHeader closeButton>
                <ModalTitle>{HEADER_TITLE}</ModalTitle>
            </ModalHeader>
            <ModalBody>
                <div>
                    <p>This project has one or more languages set up in the Translation Manager.</p>
                    <p>
                        To download the translation in the BRD export, select one language from the drop-down below.
                        English will always be shown as the base language.
                    </p>
                    <p>
                        If a language is selected, additional columns will be added to display the appropriate
                        translation for labels, rules and text messages.
                    </p>
                    <p>You may click Download without selecting a language to export the default language.</p>
                </div>
                <div>{CHOOSE_LANGUAGE_LABEL}</div>
                <div>
                    <Select
                        clearable={false}
                        canEnterFreeText={false}
                        searchable={false}
                        options={languageList}
                        onChange={onChangeLanguage}
                    />
                </div>
            </ModalBody>
            <ModalFooter>
                <Button bsStyle="primary" onClick={handleDownload}>
                    {DOWNLOAD_BUTTON_TEXT}
                </Button>
                <Button onClick={handleCancel}>{CANCEL_BUTTON_TEXT}</Button>
            </ModalFooter>
        </Modal>
    );
};

export async function showChooseLanguageModal(props: ChooseLanguageModalProps): Promise<void> {
    await ReactDOM.render(<ChooseLanguageModal {...props} />, getModalRoot());
}

export async function hideChooseLanguageModal(): Promise<void> {
    const modalRoot = getModalRoot();
    modalRoot && ReactDOM.unmountComponentAtNode(modalRoot);
}

Here are the tests that I’ve written.

import { render, fireEvent, screen } from '@testing-library/react';
import React from 'react';
import { act } from 'react-dom/test-utils';

import { ChooseLanguageModal } from '../ChooseLanguageWindow.react';

describe('ChooseLanguageModal', () => {
    const languageList = [
        { id: '1', value: 'en', name: 'English' },
        { id: '2', value: 'fr', name: 'French' },
        { id: '3', value: 'es', name: 'Spanish' },
    ];
    const onDownloadLanguage = jest.fn();
    const handleDownload = jest.fn();
    const handleCancel = jest.fn();

    test('should call onDownload when download button is clicked', async () => {
        await act(async () => {
            render(
                <ChooseLanguageModal
                    languageList={languageList}
                    onDownloadLanguage={onDownloadLanguage}
                    onDownload={handleDownload}
                    onCancel={handleCancel}
                />
            );
        });

        const downloadButton = screen.getByText('Download');
        fireEvent.click(downloadButton);

        expect(handleDownload).toHaveBeenCalled();
    });

    test('should call onCancel when cancel button is clicked', async () => {
        await act(async () => {
            render(
                <ChooseLanguageModal
                    languageList={languageList}
                    onDownloadLanguage={onDownloadLanguage}
                    onDownload={handleDownload}
                    onCancel={handleCancel}
                />
            );
        });

        const cancelButton = screen.getByText('Cancel');
        fireEvent.click(cancelButton);

        expect(handleCancel).toHaveBeenCalled();
    });
});

You’ll notice that both tests are closely identical, obviously except for the fireEvent. It fails every time.

` ● ChooseLanguageModal › should call onCancel when cancel button is clicked

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

  48 |         fireEvent.click(cancelButton);
  49 |
> 50 |         expect(handleCancel).toHaveBeenCalled();
     |                              ^
  51 |     });
  52 | });
  53 |`

I’ve tried running only the onCancel test but it still fails.

JavaScript quiz with score null points

I have a little issue with a piece of code in a project: I programmed a multiple choice quiz and I want to show an image and a message if the user has a certain number of points at the end. It actually works but not if the user has zero points.

function finalScore() {
  let endScore = parseInt(document.getElementById("score-correct").innerText);
  document.getElementById("score-correct").innerText = endScore + 1;

  // Level easy
  if (getLevel === "easy") {
    if (endScore > 3) {
      scoreMessage.innerText = "You are a true magic genius! Be ready for your owl from Hogwarts.";
      scoreImage.innerHTML = "<img src='" + imageDumbledore + "' class='img-fluid p-2'>";
    } else if (endScore === 3) {
      scoreMessage.innerText = "You're on a good way!";
      scoreImage.innerHTML = "<img src='" + imageHermione + "' class='img-fluid p-2'>";
    } else if (endScore === 2) {
      scoreMessage.innerText = "Not bad, but it could be better...";
      scoreImage.innerHTML = "<img src='" + imageHarry + "' class='img-fluid p-2'>";
    } else if (endScore <= 1) {
      scoreMessage.innerText = "Mnnnaa, maybe you'll try again?";
      scoreImage.innerHTML = "<img src='" + imageRon + "' class='img-fluid p-2'>";
    }
  } 
}

I tried to set the else if to endScore === 0 and write an else statement, but it doesn`t help. And to be honest: I have no idea why.

Can you help me? That would be amazing!

Request failed for fedex API in google sheets app scripts

I am currently trying to integrate fedex tracking into google sheets by using fedex api. I have gotten to this far but am now receiving error code 400 from fedex.

I am receiving an error code from fedex (return code 400)

Exception: Request failed for https://apis.fedex.com returned code 400. Truncated server response: {"transactionId": "bdc46ab9-8aa0-4854-baa7-5526739c0fb9","errors":[{"code":"BAD.REQUEST.ERROR","message":"The given JWT is invalid. Please modify y... (use muteHttpExceptions option to examine full response) trackPackage
@ Code.gs:10

Sorry I am not a developer so if there are any errors or mistakes please let me know

The code I was running was:

function trackPackage(trackingNumber) {

  // Get the FedEx API key and secret from the Google Sheet
  var sheet = SpreadsheetApp.getActiveSpreadsheet();

  var apiKey = sheet.getRange('A2').getValue();
  var apiSecret = sheet.getRange('B2').getValue();

  // Create a new request
  var request = UrlFetchApp.fetch('https://apis.fedex.com/track/v1/trackingnumbers', {
    method: 'POST',
    body: JSON.stringify({
      tracking_numbers: [trackingNumber]
    }),
    headers: {
      'Content-Type': 'application/json',
      'X-locale': 'en_US',
      'Authorization': 'Bearer ' + "l736f80=====14243==ca0dda" + ':' + "68938dba=====c9c6==d55ca"
    }
  });

  // Handle the response
  request.onResponse(function(response) {
    if (response.status === 200) {
      // The request was successful, so parse the JSON response
      var responseData = JSON.parse(response.getContentText());

      // Loop through the tracking results and add them to the Google Sheet
      for (var i = 0; i < responseData.tracking_results.length; i++) {
        var result = responseData.tracking_results[i];

        // Add the tracking number to the Google Sheet
        sheet.getRange('A' + (i + 1)).setValue(result.tracking_number);

        // Add the status to the Google Sheet
        sheet.getRange('B' + (i + 1)).setValue(result.status);

        // Add the location to the Google Sheet
        sheet.getRange('C' + (i + 1)).setValue(result.location);

        // Add the date and time to the Google Sheet
        sheet.getRange('D' + (i + 1)).setValue(result.date_time);
      }
    } else {
      // The request failed, so display an error message
      alert('Error: ' + response.status);
    }
  });
}

I have tried to rerun and the script and but cannot identify what error code 400 means

WebGPU “The operation failed for an operation-specific reason”

I’ve been experimenting with WebGPU, and I am continually faced with this error whenever I perform anything on the device using the API:

ID3D12Device::GetDeviceRemovedReason failed with DXGI_ERROR_DEVICE_HUNG (0x887A0006)
 - While handling unexpected error type Internal when allowed errors are (Validation|DeviceLost).
    at CheckHRESULTImpl (....third_partydawnsrcdawnnatived3dD3DError.cpp:96)
    at CheckAndUpdateCompletedSerials (....third_partydawnsrcdawnnatived3d12DeviceD3D12.cpp:372)
    at CheckPassedSerials (....third_partydawnsrcdawnnativeDevice.cpp:769)
    at Tick (....third_partydawnsrcdawnnativeDevice.cpp:1336)

Subsequent operations elicit this (rather generic, as it pops up in a variety of situations not related to WebGPU) error:

Uncaught (in promise) DOMException: The operation failed for an operation-specific reason

I’m running on Windows 10, and tested on Chrome, MSEdge, and Opera, all running on Chromium 114. I’ve tried WebGPU on a device with very similar specs, and unfortunately or not, it worked without errors. My current GPU is Intel(R) HD Graphics Family.

I conclude that this error is device specific, but I don’t think I’m the only one that has this issue. (Googling the first error comes up with a lot of gaming-related articles using MS Direct3D.)

Judging from the (former) error message, that just looks like a side effect of the issue, which caused the device to be removed, creating another error. I also took a look at the function’s docs. The error code 0x887A0006 is correlated with the device being “hung” as noted in the docs, with the following:

The application’s device failed due to badly formed commands sent by the application. This is an design-time issue that should be investigated and fixed.

I have no idea what might be the cause, and it shouldn’t be an issue with my JS code as other devices can run it just fine.

I’ve also monitored my computer resources but nothing seemed to surpass 80%.


Take this bare bones example from the WebGPU codelab that’s enough to cause the error on my device:

(async() => {
  const canvas = document.querySelector("canvas");

  // WebGPU device initialization
  if (!navigator.gpu) {
    throw new Error("WebGPU not supported on this browser.");
  }

  const adapter = await navigator.gpu.requestAdapter();
  if (!adapter) {
    throw new Error("No appropriate GPUAdapter found.");
  }

  const device = await adapter.requestDevice();

  // Canvas configuration
  const context = canvas.getContext("webgpu");
  const canvasFormat = navigator.gpu.getPreferredCanvasFormat();
  context.configure({
    device: device,
    format: canvasFormat,
  });

  // Clear the canvas with a render pass
  const encoder = device.createCommandEncoder();

  const pass = encoder.beginRenderPass({
    colorAttachments: [{
      view: context.getCurrentTexture().createView(),
      loadOp: "clear",
      clearValue: {
        r: 0,
        g: 0,
        b: 0.4,
        a: 1.0
      },
      storeOp: "store",
    }]
  });

  pass.end();

  device.queue.submit([encoder.finish()]);
})()
<canvas width="512" height="512"></canvas>

Anyone else experience this and found a solution?

Calling resolve() on promise won’t change its status which will stay on pending

I have the following code

import fetch, { Response } from "node-fetch"
import { joinCookieNameAndValue } from "../string-manipulation"
import item from "../../types/data-types/item"

const scan = (name: string, page: number): Promise<item | void> => new Promise(async (resolve, reject) => {
    const itemsRes: Response = await fetch(`url`, {
        method: "GET",
        headers: {
            Cookie: joinCookieNameAndValue("cookie-name", <string> process.env.COOKIE_VALUE)
        }
    })

    if (!itemsRes.ok) {
        return reject(new Error(`Could not fetch items: request failed with status code ${itemsRes.status}`));
    }

    const items: Array<item> = await itemsRes.json();
    const item_: item | undefined = items.find(i => i.name == name);

    if (items.length == 0) {
        return resolve();
    }

    if (!item_) {
        return scan(name, ++page);
    }

    resolve(item);
})

export default async (name: string) => scan(name, 1);

The promise above is awaited in another script but the code after it won’t ever run as the promise never gets resolved even thought the code inside the items.length == 0 if statement runs.

I can’t print this to do list using vue and i don’t have a clue (novice dev)

As the title says.

I want to print a list on page using the create app from vue but no matter what I do and how I write, it just won’t print on page.
I am a novice in this so I am for sure messing something up.

This is my html with the v for loop

<body>
    <script src="https://unpkg.com/vue@3/dist/vue.global.js"></script>
      
     <div id="app">
        <header class="text-center">
            <h1 class="fw-bold">
                My ToDoList
            </h1>
        </header>
        <div class="my_list_container m-auto">
            <ul>
                <li v-for ="(items, index) in toDoList">
                    <span> {{ items.text }} </span>
                    <i class="fa-solid fa-xmark fa-xl" style="color: #ff0000;"></i>
                </li>
            </ul>
        </div>
        <div class="my_input_button">
            <input type="text" placeholder="write here your ToDo">
            <button>
                Aggiungi alla lista
            </button>
        </div>
     </div>
    
    <script src="script.js"></script>
</body>

this is the js

const {createApp} = Vue

createApp ({
    data () {
        return{
            ToDoList: [{
                text: "Capire qualcosa della programmazione",
                done: false
            },
    
                {text: "Studiare la teoria",
                done: false
            },
    
                {text: "Applicare la teoria alla pratica",
                done: true
            },
    
                {text: "Non funziona nulla",
                done: true
            },
    
                {text: "Piangere sul divano del napoli",
                done: false
            }],
            newToDo  : "",
        }
    },
}).mount ("#app")

Thank you

React pie chart tooltip percentage not showing

I need the numbers to be shown as percentages on hover. I’m using a callback in options, which seems to be the suggested solution, but it’s not working. Here’s the link to the editor and the options that I’m using https://stackblitz.com/edit/stackblitz-starters-ntdk3g?file=src%2FApp.js

const option = {
  tooltips: {
    callbacks: {
      label: function(tooltipItem, data) {
        var dataset = data.datasets[tooltipItem.datasetIndex];
        var meta = dataset._meta[Object.keys(dataset._meta)[0]];
        var total = meta.total;
        var currentValue = dataset.data[tooltipItem.index];
        var percentage = parseFloat((currentValue/total*100).toFixed(1));
        return currentValue + ' (' + percentage + '%)';
      },
      title: function(tooltipItem, data) {
        return data.labels[tooltipItem[0].index];
      }
    }
  }
}

How can I access routes object from React Router v6 in a service without a circular dependency?

I’m using an RTK Query service to grab routes from an API. The API returns a path starting with / and does not include the base URL. The base URL for an endpoint depends on if that page has been migrated to the SPA. So I want to check the routes in the SPA: If the routes object contains the path for that link, I’ll treat the link based on SPA Routing, otherwise I’ll add the base URL of the legacy application.

I was disappointed to find that React Router v6 doesn’t seem to provide access to its internal routes object. There is a matchRoutes function, so I need access to the routes object, but that was in main. So I refactored it to routes.js:

import App from "./app";
import ErrorPage from "./pages/error";
import FunctionalityPage from "./pages/examplefunctionality";

const routes = [
  {
    path: "/",
    element: <App />,
    errorElement: <ErrorPage />,
    children: [
      {
        path: "/func",
        element: <FunctionalityPage />,
      },
    ],
  },
];

export default routes;

Then I import this into main.jsx and pass it to a RouterProvider:

import store from "./store";
import routes from "./routes";
// ... skipped for brevity
const router = sentryCreateBrowserRouter(routes, {
  basename: import.meta.env.BASE_URL,
});

ReactDOM.createRoot(document.getElementById("root")).render(
  <React.StrictMode>
    <Provider store={store}>
      <RouterProvider router={router} />
    </Provider>
  </React.StrictMode>
);

Then I’m able to import it in my RTK Query service.js as well:

import { createApi, fetchBaseQuery, retry } from "@reduxjs/toolkit/query/react";
import { matchRoutes } from "react-router-dom";
import { routes } from "../routes";

const baseQuery = retry(
  fetchBaseQuery({
    baseUrl: import.meta.env.VITE_BASE_API_URL,
  })
);

export const service = createApi({
  reducerPath: "serviceApi",
  baseQuery,
  endpoints: (builder) => ({
    getMenu: builder.query({
      query: () => `menu/getmenuitems`,
      transformResponse: (data) => {
        const updateHref = (item) => {
          if (item.href) {
            const match = matchRoutes(routes, item.href);
            if (match && match.length > 0) {
              item.to = item.href;
              delete item.href;
            } else {
              item.href = import.meta.env.VITE_LEGACY_URL + item.href;
            }
          }
          if (item.children) {
            item.children.forEach(updateHref);
          }
        };
        data.forEach(updateHref);
        return data;
      },
    }),
    getData: // ... skipped for brevity
  }),
});

export const {
  useGetMenuQuery,
  useGetDataQuery,
} = service;

Functionally, this worked perfectly: I’m able to navigate to either the SPA with a Link or the legacy site with an href, by passing this structure into my component. The trouble starts when I run eslint: I get an error from import/no-cycle in app.jsx, examplefunctionality.jsx, routes.jsx, and service.js, because ExampleFunctionality imports getDataQuery from service.js, which therefore imports the routes, which imports the app, and the cycle continues.

Do I have to split up the api service? Ideally I’d like to just have the one API service, since its all connecting to the same API and the RTK Query docs recommend that approach. Is this a normal pattern? How should I structure my code to avoid the circular dependency, and maintain the organization?

What I really want is a hook that will expose the actual routes object from the router.

babel-preset-react-app, is importing the “@babel/plugin-proposal-private-property-in-object” package without declaring it in its dependencies

my issue is that I’ve tried to create a new react project and after a lot of issues with vulnerabilities I managed to solve some of them, one of the main instructions was adding this line:

"overrides": {
    "@svgr/webpack": "$@svgr/webpack"
  },

into my package.json file.
Once I’ve done that I had to delete my node_modules folder and reuse npm install and now I am getting a babel error after typing npm start.

One of your dependencies, babel-preset-react-app, is importing the
"@babel/plugin-proposal-private-property-in-object" package without
declaring it in its dependencies. This is currently working because
"@babel/plugin-proposal-private-property-in-object" is already in your
node_modules folder for unrelated reasons, but it may break at any time.

babel-preset-react-app is part of the create-react-app project, which
is not maintianed anymore. It is thus unlikely that this bug will
ever be fixed. Add "@babel/plugin-proposal-private-property-in-object" to
your devDependencies to work around this error. This will make this message
go away.

I tried to search for the solution over the internet and I found only one that tells me to add this plugin to my devDependencies which did not work, and I also found a solution that tells to type CI= npm run build which didn’t work either.

This is what I’m encountering when typing npm list @babel/plugin-proposal-private-property-in-object :


npm ERR! code ELSPROBLEMS
npm ERR! invalid: @babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2 C:UsersOmri-PCDesktopKeeperAppnode_modules@babelplugin-proposal-private-property-in-object
[email protected] C:UsersOmri-PCDesktopKeeperApp
├── @babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2 invalid: "^x.x.x" from the root project
└─┬ @svgr/[email protected] overridden
  └─┬ @babel/[email protected]
    └── @babel/plugin-proposal-private-property-in-object@7.21.0-placeholder-for-preset-env.2 deduped invalid: "^x.x.x" from the root project

And that’s how my package.json file looks like if it somehow helps to figure:

{
  "name": "keeper-app-part-1-starting",
  "version": "1.0.0",
  "description": "",
  "keywords": [],
  "main": "src/index.js",
  "dependencies": {
    "react": "18.2.0",
    "react-dom": "18.2.0"
  },
  "devDependencies": {
    "@svgr/webpack": "^8.0.1",
    "react-scripts": "5.0.1",
    "typescript": "5.1.3"
  },
  "overrides": {
    "@svgr/webpack": "$@svgr/webpack"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}

Hope that I gave you enough information in order to help me solve this issue, thanks a lot!

Django channel web socket to console.log() to the Browser

I am using npm wscat package to to send the message to django channels, when the
message is sent through the terminal, it prints on the server console as expected, how ever when I send it
to the browser the console is not logging the message

following is my working code:

#consumer.py

from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass
    
    def receive(self, text_data):
        message_content = text_data
        print(message_content)
        self.send(text_data=message_content)

#routing.py

from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/$', consumers.ChatConsumer.as_asgi()),
]

#index.html

...
<script>

 let chat = null;

 function connect() {
  chat = new WebSocket("ws://localhost:8000/ws/chat/")

  chat.onopen = function (e) {
   console.log("Successfully connected to the WebSocket.");
  }

  chat.onmessage = function (result) {
   console.log(result.data);
   }

  chat.onerror = function (err) {
   console.log("WebSocket encountered an error: " + err.message);
   console.log("Closing the socket.");
  }
  chat.onclose = function (event) {
   console.log('WebSocket connection closed.');
  };
  <!--  -->
 }

 connect();
</script>
...

In the brower chat.onopen function works perfectly, and is diplayed in the browser,
however for some reason chat.onmessage function never gets executed.