How to add cancel a previously sent request in redux-query using abortcontroller

I have a searchBar in which when user types characters we fetch data from backend I if another request comes we need to cancel the previously sent request how to achieve that in redux-query


import { apiSlice } from './apiSlice'
export const searchSlice = apiSlice.injectEndpoints({
  endpoints: (builder) => ({
    getSearch: builder.query({
      query: (searchTerm: string) => ({
        url: `/search/all?search_term=${searchTerm}`,
        method: 'GET',
      }),
      transformResponse: async (responseData) => {
        return responseData
      },
    }),
  }),
})

export const { useGetSearchQuery } = searchSlice

access array items with key & index

I try to create a “keyed” array, where items can be accessed by the index (like a regular array) and a .key property defined in the item object.

The problem(s):

  • I have concern about the consistency
  • Array methods can be overridden
  • Implement all methods (.slice, .splice. etc.)
class Commands extends Array {

    constructor(items) {

        super(...items);

        items.forEach((item) => {
            this[item.key] = item;
        });

    }

    push(...items) {

        super.push(...items);

        items.forEach((item) => {
            this[item.key] = item;
        });

    }

}

const commands = new Commands([{
    key: "a",
    name: "A"
}, {
    key: "b",
    name: "B"
}, {
    key: "c",
    name: "C"
}]);


console.log("commands", commands);

console.log("item a", commands.a);
console.log("item c", commands[2]);

commands.a.name = "foo";
//commands.slice(0, 1); // throws error "TypeError: Spread syntax requires ...iterable[Symbol.iterator] to be a function"

console.log(commands);

So my question is: Is this a good approach (in terms of “for most use cases”), or should handle it in a other way, e.g. wrap the array in a proxy and handle the “get by key” stuff in get trap, or something complete else?

Error retrieving data from Localhost with PHP script

I want to fill my table with data from my localhost database, which i managed to do. when i delete an employee, i would like to retrieve their first and last name based on their id. unfortunately, i am not sure where my code is going wrong as the same code works for other queries.

I am a student and practising so apologies if my code is not up to code. I’m learning by myself and exploring php at the moment.

PHP scipt:

<?php
    ini_set('display_errors', 'On');
    error_reporting(E_ALL);

    $executionStartTime = microtime(true);

    include("config.php");

    header('Content-Type: application/json; charset=UTF-8');

    $conn = new mysqli($cd_host, $cd_user, $cd_password, $cd_dbname, $cd_port, $cd_socket);

    if (mysqli_connect_errno()) {
        $output['status']['code'] = "300";
        $output['status']['name'] = "failure";
        $output['status']['description'] = "database unavailable";
        $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
        $output['data'] = [];
        mysqli_close($conn);
        echo json_encode($output);
        exit;
    }

    // First query to retrieve personnel data based on ID
    $query = $conn->prepare('SELECT `id`, `firstName`, `lastName`, `email`, `departmentID` FROM personnel WHERE `id` = ?');
    $query->bind_param("i", $_POST['id']);
    $query->execute();

    if ($query === false) {
        $output['status']['code'] = "400";
        $output['status']['name'] = "executed";
        $output['status']['description'] = "query failed";
        $output['data'] = [];
        mysqli_close($conn);
        echo json_encode($output);
        exit;
    }

    $result = $query->get_result();
    $personnel = [];

    while ($row = mysqli_fetch_assoc($result)) {
        array_push($personnel, $row);
    }

    if (empty($personnel)) {
        $output['status']['code'] = "404";
        $output['status']['name'] = "not found";
        $output['status']['description'] = "no personnel found with the provided ID";
        $output['data'] = [];
        mysqli_close($conn);
        echo json_encode($output);
        exit;
    }

    // Second query to retrieve department data
    $query = 'SELECT id, name from department ORDER BY name';
    $result = $conn->query($query);

    if (!$result) {
        $output['status']['code'] = "400";
        $output['status']['name'] = "executed";
        $output['status']['description'] = "query failed";
        $output['data'] = [];
        mysqli_close($conn);
        echo json_encode($output);
        exit;
    }

    $department = [];

    while ($row = mysqli_fetch_assoc($result)) {
        array_push($department, $row);
    }

    $output['status']['code'] = "200";
    $output['status']['name'] = "ok";
    $output['status']['description'] = "success";
    $output['status']['returnedIn'] = (microtime(true) - $executionStartTime) / 1000 . " ms";
    $output['data']['personnel'] = $personnel;
    $output['data']['department'] = $department;

    mysqli_close($conn);

    echo json_encode($output);
?>

JS Script:

let addPersonnel = function (selectVal, departments) {
  let perLocObj = $.grep(departments, function (department, i) {
    return department.department.toLowerCase() === selectVal.toLowerCase();
  });
  perLocInput = perLocObj[0].location;
  $("#locationInput").val(perLocInput);
};

let fillTable = (data) => {
  $("#personnelTableBody").empty();
  for (let i = 0; i < data.length; i++) {
    let row = $(`<tr id=employeeRow'${[i]}'>`);
    // console.log(data[0]);

    //Name
    let nameTableCell = $("<td>")
      .addClass("align-middle text-nowrap")
      .html(`${data[i].firstName}, ${data[i].lastName}`);

    row.append(nameTableCell);

    //Job Title
    let jobTableCell = $("<td>")
      .addClass("align-middle text-nowrap d-none d-sm-table-cell")
      .html(data[i].jobTitle)
      .addClass("text-start mb-0");

    row.append(jobTableCell);

    //Department
    let departmentCell = $("<td>")
      .addClass("align-middle text-nowrap d-none d-md-table-cell")
      .html(data[i].department);

    row.append(departmentCell);

    //Location
    let locationsCell = $("<td>")
      .addClass("align-middle text-nowrap d-none d-lg-table-cell")
      .html(data[i].location);

    row.append(locationsCell);

    //Email
    let emails = $("<td>")
      .addClass("align-middle text-nowrap d-none d-xl-table-cell")
      .html(data[i].email);

    row.append(emails);

  
    // -- BUTTONS -- //
    let buttonCells = $("<td>").addClass("align-middle text-end text-nowrap");
    let editButtons = $("<button>")
      .addClass("btn btn-primary btn-sm m-1")
      .attr("data-bs-target", "#editEmpModal")
      .attr("data-id", data[i].id)
      .attr("data-bs-toggle", "modal");
    let editIcons = $("<i>").addClass("fa-solid fa-pencil fa-fw");
    let deleteButtons = $("<button>")
      .addClass("btn btn-primary btn-sm")
      .attr("data-bs-target", "#deleteEmpModal")
      .attr("data-id", data[i].id)
      .attr("data-bs-toggle", "modal");
    let deleteIcons = $("<i>").addClass("fa-solid fa-trash fa-fw");

    editButtons.append(editIcons);
    deleteButtons.append(deleteIcons);
    buttonCells.append(editButtons);
    buttonCells.append(deleteButtons);
    row.append(buttonCells);

    $("#personnelTableBody").append(row);
  }
  $("#empNumber").html(`${data.length} Employees`);
};

// Personnal Delete Tab
// -- Delete Employee Modal Shows -- //
$("#deleteEmpModal").on("show.bs.modal", function (e) {
  $.ajax({
    url: "libs/php/getPersonnelByID.php",
    type: "POST",
    dataType: "json",
    data: {
      id: $(e.relatedTarget).attr("data-id"), // Retrieves the data-id attribute from the calling button
    },
    success: function (result) {
      if (result.status.code == 200) {
        console.log(result);
        personnelId = result.data.personnel[0].id;
        $("#deleteEmpMessage").html(
          `Are you sure you want to delete <b>${result.data.personnel[0].firstName} ${result.data.personnel[0].lastName}<b>?`
        );
      } else {
        $("#deleteEmpModal .modal-title").replaceWith("Error retrieving data");
      }
    },
    error: function (jqXHR, textStatus, errorThrown) {
      $("#deleteEmpModal .modal-title").replaceWith(
        "Error cannot retrieving data"
      );
    },
  });
});

// -- Delete Employee Confirm Routine -- //
$("#confirmdelEmp").on("click", function (e) {
  $.ajax({
    url: "libs/php/deleteEmployee.php",
    type: "POST",
    dataType: "json",
    data: {
      id: personnelId,
    },
    success: function (result) {
      if (result.status.code == 200) {
        fillTable(result.data);
        $("#deleteEmpModal").modal("hide");
        delEmpToast.show();
      } else {
        console.log("failed");
      }
    },
    error: function (jqXHR, textStatus, errorThrown) {},
  });
});

$("#cancelEditEmpBtn").on("click", function () {
  $("#editEmpTitle").html("");
  $("#editFirstName").val("");
  $("#editLastName").val("");
  $("#editEmail").val("");
  $("#editJob").val("");
});

convert a index.android.bundle file back into javascript code

I’m curious if there’s a way to revert the index.android.bundle file I obtained from my app back into JavaScript. I want to check if it still functions properly. Could you suggest the most effective method for accomplishing this?

I experimented with hermes-dec, but it only generates JavaScript pseudo code, which isn’t particularly helpful for my needs.

maybe more clear:
I’m looking to revert the index.android.bundle file from my app back into JavaScript code to verify its functionality. I tried using hermes-dec, but it only generates JavaScript pseudo code, which doesn’t fully meet my needs. Do you have any suggestions for a more effective method to achieve this?

How to whitelabel Wazuh beyond configuration files?

I am tasked with whitelabeling Wazuh. I have so far edited the opendashboard yaml configuration file and changed all images/strings that are part of the official documentation. To be more specific, I want to be able to edit the following elements of the UI by changing the banding from Wazuh to anything else:

1.
Changing the title to say CRYPTANK rather than Wazuh – CRYPTANK
Tab title
2. Renaming side navigation from Wazuh to CRYPTANK
Side navigation
3.
In Management > Rules you can see often the name Wazuh appearing
enter image description here
4.
Analogous to Management > Status
Management > Status
5.
Management > Logs
Logs

So far, I have looked at the following information regarding whitelabeling:

https://github.com/wazuh/wazuh-dashboard-plugins/issues/4392

https://github.com/wazuh/wazuh-dashboard-plugins/issues/4269

https://github.com/wazuh/wazuh/discussions/18571

https://opensearch.org/docs/1.2/dashboards/branding/

https://forum.opensearch.org/t/customizing-the-kibana-login-page/3697

I also raised an issue in the Wazuh github repo: https://github.com/wazuh/wazuh-dashboard/issues/178 The answer I received was consistent with the research – whitelabeling is very limited at this point. I was pointed to the OpenDashboard github repo where I also raised an issue with the same information.

My question is whether you see any way the UI can be customized beyond the configuration files. My idea is to write somewhere custom css rules and js but so far I don’t know exactly where. Any help on this would be appreciated.

How to Implement Accident Alert Feature in Google Maps Plugin?

I am developing a navigation application based on Google Maps with the goal of alerting users when they navigate through potentially dangerous areas. Specifically, I have a file containing latitude and longitude information of accident locations, and I want the application to alert the user if their navigation route passes through these locations.

I hope to be able to perform this function on the web page on my mobile phone just like the app that uses maps every day.

Google authentication not visible on mobile devices

Well, basically I’m working on a login for an access control I’m working on so I ended up with google api, and since I’m new to this I have had a lot of troubles, currently I’m really happy because I got the login to work with google gsi library and I’m getting the google accounts data that I need, the problem comes with the UI, because I have a cointainer with this elements:

<div id="btnWrap">
            <!-- Sign In With Google button with HTML data attributes API -->
            <div id="g_id_onload"
            data-client_id="here i have my proyect id"
            data-context="signin"
            data-ux_mode="popup"
            data-callback="handleCredentialResponse"
            data-auto_prompt="true"
            data-auto_select="true">
            </div>

            <div class="g_id_signin"
            data-type="icon"
            data-shape="circle"
            data-theme="outline"
            data-text="signin_with"
            data-size="large"
            data-logo_alignment="left">
            </div>

        </div>

and when I open this on pc it works just perfect, but when I open it with a mobile device it opens the new popup tab but it is completely blank, and since it’s a phone I can’t open the console to check the issue, I know there’s another way to work with this ui using the redirect ux mode, but it requires a different configuration and I got a lot of errors,

so as a summary, my question is why the following interface is not showing on mobile devices
login interface

well, I was expecting to the ui to work just perfectly on any device

Google Calendar appendPre is not defined

I use Google Calendar to write the itinerary according to the document, and it can be added to the calendar normally on the project, but it will prompt Uncaught ReferenceError: appendPre is not defined. Does anyone know why this is
enter image description hereenter image description here

I tried writing according to the document, but it still didn’t work

var event = {
‘summary’: ‘DCH Toolbox – Repair Appointment ‘+this.arr?.serviceDate.slice(8,10)+’/’+this.arr?.serviceDate.slice(5,7)+’/’+this.arr?.serviceDate.slice(0,4),
‘location’: address,
‘description’: ‘Repair appointment Ref. code: ‘+this.arr.serviceOrderId+’ has been confirmed.’,
‘start’: {
‘date’: this.arr?.serviceDate
},
‘end’: {
‘date’: this.arr?.serviceDate
},
‘attendees’: [
{’email’: this.arr.logisticsElectronicAddressLocatorEmail}
],
‘reminders’: {
‘useDefault’: false,
‘overrides’: [
{‘method’: ’email’, ‘minutes’: 24 * 60},
{‘method’: ‘popup’, ‘minutes’: 10}
]
}
};
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: clientId,
scope: ‘https://www.googleapis.com/auth/calendar’,
callback: ”, // defined later
});
gisInited = true;
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
console.log(‘gapi.client’,gapi.client);
if(gapi.client.calendar) {
var request = gapi.client.calendar.events.insert({
‘calendarId’: ‘primary’,
‘resource’: event
});
console.log(‘request’,request);
await request.execute(function(event2) {
appendPre(‘Event created: ‘ + event2.htmlLink);
});
}
};

Find Specific widget Javascript

I have build a roofing service base website on wordpres. I have used the trigger in the mobile view. But sometime it does not word due to over optimisation. The question is that how we can find the specific javascript from the below coding that it is showin the trigger and responsible for its working.

Inspect the page from this url for checkin issue. https://vistaroofinglincoln.co.uk

I have inspect the page elements and try to find the JS coding for trigger but I found many coding lines for it and could not identify that which is responsible for the trigger

Is there ever a reason to use generators rather than promise-based async code?

I know that generators paired with iterators can be used to write async code, but what’s the benefit of using it? I’ve heard it offers more fine grained control than promises, but so far I haven’t seen a case of that… I also believe I’m right in saying that while generators where considered for the implementation of async/await, all JS engines use promises to implement it. Here’s an example of using generators to handle async operations:

function fetchData() {
  return new Promise((resolve, reject) => {
    // Generator function
    function* fetchGenerator() {
      try {
        console.log("Fetching data...");
        const data1 = yield fetch('https://api.example.com/data1');
        console.log("Data 1 fetched");
        const data2 = yield fetch('https://api.example.com/data2');
        console.log("Data 2 fetched");
        resolve({ data1, data2 });
      } catch (error) {
        reject(error);
      }
    }
    
    // Create generator iterator
    const generator = fetchGenerator();
    
    // Function to handle generator iteration
    function handleAsync(generator, yieldedValue) {
      const { value, done } = generator.next(yieldedValue);
      if (done) {
        resolve(value);
      } else {
        Promise.resolve(value)
          .then(
            result => handleAsync(generator, result),
            error => generator.throw(error)
          );
      }
    }
    
    handleAsync(generator);
  });
}

fetchData().then(result => {
  console.log("All data fetched:", result);
}).catch(error => {
  console.error(“Fetching data:", error);
});

rqlite, nextjs, typeorm pain of `id:null` for an insert to a table

Issue:

  • i got an AUTOINCREMENT, number field ‘id’ in my table (DB: rqlite)
  • when i insert a partial row (no mandatory fields except primary key) i don’t get the id value back from typeorm which was inserted in the DB
  • following in my setup and the multiple code i tried (check the service below)

entity definition

export class Requests {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ nullable: true })
  name: string;

...}

migration table

CREATE TABLE "requests" (
      id INTEGER PRIMARY KEY AUTOINCREMENT,
      name varchar,
...);

in the service (issue here)

unable to get the auto-incremented value back despite create/insert/upsert/save… i need to know the id (primary key) of the row that was inserted


  public async saveRequest(passedPartialRequest: Partial<Requests> | any) {
    // case 1: if we don't provide an id, we get "TypeORMError: Cannot update entity because entity id is not set in the entity."
    // if we provide id:null or id:0, we get id: null or id:0 (even though the correct incremented id is created in the DB)
    const case1 = await this.requestsRepository.save({
      ...passedPartialRequest,
      id: null,
    });

    // case 2: inserted a row but id came back as undefined (from the DB)
    const case2 = await this.requestsRepository.create({
      passedPartialRequest,
    });

    // case 3: need to provide id, else we get "TypeORMError: Cannot update entity because entity id is not set in the entity."
    const case3 = await this.requestsRepository.insert({
      ...passedPartialRequest,
      id: null,
    });

    // case 4: TypeORMError: Cannot update entity because entity id is not set in the entity,
    // if we provide null, we get identifier: null
    const saved4 = await this.requestsRepository
      .createQueryBuilder()
      .insert()
      .values({
        ...passedPartialRequest,
        id: null,
      })
      .execute();

    // case 5: this also returns identifier: null - we need to provide id:null to prevent the TypeORMError above
    const case5 = await this.requestsRepository.upsert(
      { ...passedPartialRequest, id: null },
      ['id']
    );

    // case 6: OUTPUT or RETURNING clause only supported by Microsoft SQL Server or PostgreSQL or MariaDB databases.
    const case6 = await this.requestsRepository
      .createQueryBuilder()
      .insert()
      .into('requests')
      .values([passedPartialRequest])
      .returning('INSERTED.*')
      .printSql()
      .execute();    

Typescript doesn’t work for client side Javascript following instructions [duplicate]

I followed the instructions to setup a typescript project in vscode and right off the bat I’m getting errors from typescript after creating the tsconfig it created.

When I run my web page in a browser I get an error:

Project:
enter image description here

Error:
enter image description here

The suggestions say to change module to “ES6”. As soon as I do that imports break and can’t be found.

enter image description here

enter image description here
So then it suggests I change to nodenext and I do that and the error in vscode goes away but the same error occurs in the browser!

enter image description here

enter image description here

It seems Typescript can’t export to client side Javascript with default settings.

Best Practices for Using Non-Rendering State Management Components in React?

I’m exploring a pattern in React where I use non-rendering components to manage state and side effects. I find it useful for preventing unnecessary re-renders and keeping the code clean. However, I’m unsure if there are any established best practices or recommendations for this pattern.

Here’s an example of the pattern:

<Provider>
  {children}
  <StateReactor />
</Provider>

The StateReactor component returns null and is sometimes memoized:

const StateReactor = React.memo(() => {
  const a = useAStore((s) => s.online);
  const b = useBStore();

  useEffect(() => {
    b.setState({ ok: true });
  }, [x]);
  return null;
});

The StateReactor component manipulates state, connects to stores, and performs side effects without rendering anything. This approach helps prevent re-renders and makes the code clearer.

Real-World Use Cases

  1. Composing Multiple States

    CurrentListTableQueryReactor reflects the query results to the table store. This allows the standalone table component to be reused in different places, and the query logic can also be reused.

    export const CurrentListTableQueryReactor = () => {
      let store = useReactTableStore();
      let { useListQuery } = useListQueryContext();
      const { data } = useListQuery();
    
      useEffect(() => {
        if (!data) return;
        store.getState().setOptions((prev) => ({
          ...prev,
          data: data.data,
          rowCount: data.total,
        }));
      }, [data]);
    
      return null;
    };
    
  2. Running One-Time Setup Logic

    While I could wrap this logic in a hook, using a component avoids re-rendering the parent component.

    export const TableInitialStateSetup: React.FC<{
      onInitialState?: (v: InitialTableState) => void;
      initialState?: InitialTableState;
    }> = ({ onInitialState, initialState }) => {
      const { defaultPageSize } = usePageSizeOptions();
      let [params] = useSearchParams();
    
      useEffect(() => {
        let base = {
          pagination: {
            pageIndex: parseInt(params.get('pageIndex') || '0') || 0,
            pageSize: parseInt(params.get('pageSize') || '0') || defaultPageSize,
          },
          sorting: initialState?.sorting || [],
        };
        let order = params.getAll('order');
        if (order.length) {
          base.sorting = order.map((v) => {
            let desc = v.startsWith('-');
            return {
              id: v.replace(/^[-+]/, ''),
              desc,
            };
          });
        }
        onInitialState?.(base);
      }, []);
    
      return null;
    };
    

Question

I’ve tried to find articles or blogs about this pattern but haven’t had much luck. Are there any established practices or recommendations for using non-rendering state management components in React? Or is there a better way to achieve similar results?

Can you append multiple children onto different lines?

I am wondering if it’s possible to append children onto different lines in JavaScript. I am trying to recreate an old Oregon Trail project and am taking a new approach at it, and when I append the existing children they show up directly next to each other. Is there a way to get them to print out on different lines.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Project</title>
        <link rel="stylesheet" href="styles.css">
    </head>
    <body>
        <div id="header">
            <h1>Oregon Trail</h1>
        </div>

        <span id="span"><button id="btn" class="btns">Lantern</button><br>
            <button id="btn1" class="btns">Lantern and butter churn</button><br>
            <button id="btn2" class="btns">Butter churn</button><br>
            <button id="btn3" class="btns">Box</button><br>     
        </span>

        <script src="script.js"></script>
    </body>
</html>
const btnElement = document.getElementById("btn");
const button = document.createElement("btn22");
const button1 = document.createElement("btn23");
button.innerText = "Yes";
button1.innerText = "No";

button.classList.add("btns");
button1.classList.add("btns");

btnElement.addEventListener("click", () => {
    document.body.appendChild(button);
    document.body.appendChild(button1);
})

I haven’t tried much other than attaching the child to a string, but nothing has worked and it doesn’t look like anyone has had this issue before.