useEffect not running in nextJS 13.4 (app router) app

i am trying to fetch data from next api route but the useEffect method is not firing up on page reload.
also i can’t make this component async as nextJS does’nt allow async functions on client components(use client)

page.tsx:

"use client";
import { useEffect, useState } from "react";
import DataTable from "./components/table";
import { Resizable } from "re-resizable";

const SamplePage: React.FC = () => {
  const [data, setData] = useState(null);
  useEffect(() => {
    fetch("/api/data")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        console.log("data");
      });
  }, []);

  console.log(data, "dataaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");

  const headers = [
    "Timestamp",
    "Purchase Id",
    "Mail",
    "Name",
    "Source",
    "Status",
    "Select",
  ];
  const rows = [
    {
      Timestamp: "2023-07-15",
      "Purchase Id": "P001",
      Mail: "[email protected]",
      Name: "John Doe",
      Source: "Web",
      Status: "Completed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-16",
      "Purchase Id": "P002",
      Mail: "[email protected]",
      Name: "Jane Smith",
      Source: "Mobile",
      Status: "Waiting",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-17",
      "Purchase Id": "P003",
      Mail: "[email protected]",
      Name: "Mike Johnson",
      Source: "Web",
      Status: "Failed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-18",
      "Purchase Id": "P004",
      Mail: "[email protected]",
      Name: "Emily Brown",
      Source: "Web",
      Status: "Completed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-19",
      "Purchase Id": "P005",
      Mail: "[email protected]",
      Name: "David Wilson",
      Source: "Mobile",
      Status: "Waiting",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-20",
      "Purchase Id": "P006",
      Mail: "[email protected]",
      Name: "Sarah Davis",
      Source: "Web",
      Status: "Failed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-21",
      "Purchase Id": "P007",
      Mail: "[email protected]",
      Name: "Alex Johnson",
      Source: "Mobile",
      Status: "Completed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-22",
      "Purchase Id": "P008",
      Mail: "[email protected]",
      Name: "Emma Smith",
      Source: "Web",
      Status: "Waiting",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-23",
      "Purchase Id": "P009",
      Mail: "[email protected]",
      Name: "James Wilson",
      Source: "Web",
      Status: "Failed",
      Select: "Select",
    },
    {
      Timestamp: "2023-07-24",
      "Purchase Id": "P010",
      Mail: "[email protected]",
      Name: "Olivia Brown",
      Source: "Mobile",
      Status: "Completed",
      Select: "Select",
    },
  ];
  const [state, setState] = useState({ width: "95%", height: "80%" });
  return (
    <>
      <Resizable
        style={{ border: "1px solid black" }}
        size={{ width: state.width, height: state.height }}
        onResizeStop={(e, direction, ref, d) => {
          setState({
            width: state.width + d.width,
            height: state.height + d.height,
          });
        }}
      >
        <DataTable
          headers={headers}
          rows={rows}
          caption="Bookings Details (pagination,sorting added)"
          sortable
          pagination
          colorScheme="teal"
        />
      </Resizable>
    </>
  );
};

export default SamplePage;

DataTable.tsx

"use client"
import {
  Table,
  Thead,
  Tbody,
  Tr,
  Th,
  Td,
  Box,
  Input,
  Flex,
} from "@chakra-ui/react";
import { useState } from "react";
import styles from "./table.module.css";
import { Button, ButtonGroup } from "@chakra-ui/react";
import {
  ChevronRightIcon,
  ChevronLeftIcon,
  SearchIcon,
  ChevronDownIcon,
  ChevronUpIcon,
} from "@chakra-ui/icons";
import dynamic from "next/dynamic";

interface DataTableProps {
  headers: string[];
  rows: Record<string, string | number>[];
  caption?: string;
  sortable?: boolean;
  pagination?: boolean;
  itemsPerPage?: number;
  tableStyling?: string;
  colorScheme?: string;
}

const DataTable: React.FC<DataTableProps> = ({
  headers,
  rows,
  caption,
  sortable,
  pagination,
  itemsPerPage,
  tableStyling,
  colorScheme,
}) => {
  const [sortConfig, setSortConfig] = useState<{
    column: string;
    ascending: boolean;
  }>({
    column: "",
    ascending: true,
  });
  const [currentPage, setCurrentPage] = useState(1);
  const [perPage, setPerPage] = useState(itemsPerPage || 5);
  const [searchTerms, setSearchTerms] = useState<{ [column: string]: string }>(
    {}
  );
  const [resizableColumns, setResizableColumns] = useState<string[]>([]);

  const handleHeaderClick = (column: string) => {
    if (!sortable) return;

    if (sortConfig.column === column) {
      setSortConfig({ ...sortConfig, ascending: !sortConfig.ascending });
    } else {
      setSortConfig({ column, ascending: true });
    }
  };

  const sortRows = () => {
    if (!sortConfig.column) return rows;

    const sortedRows = [...rows];

    sortedRows.sort((a, b) => {
      const valueA = a[sortConfig.column];
      const valueB = b[sortConfig.column];

      if (typeof valueA === "string" && typeof valueB === "string") {
        return sortConfig.ascending
          ? valueA.localeCompare(valueB)
          : valueB.localeCompare(valueA);
      } else {
        return sortConfig.ascending
          ? (valueA as number) - (valueB as number)
          : (valueB as number) - (valueA as number);
      }
    });

    return sortedRows;
  };

  const filterRows = () => {
    return rows.filter((row) => {
      return Object.entries(searchTerms).every(([column, searchTerm]) => {
        const value = row[column]?.toString().toLowerCase();
        return value?.includes(searchTerm.toLowerCase());
      });
    });
  };

  const getFilteredAndSortedRows = () => {
    const filteredRows = filterRows();
    const sortedRows = sortRows();
    return sortedRows.filter((row) => filteredRows.includes(row));
  };

  const renderRows = () => {
    const sortedAndFilteredRows = getFilteredAndSortedRows();

    const startIndex = (currentPage - 1) * perPage;
    const endIndex = startIndex + perPage;

    return sortedAndFilteredRows
      .slice(startIndex, endIndex)
      .map((row, index) => (
        <Tr key={index}>
          {headers.map((header, index) => {
            return (
              <Td key={index}>
                <Box
                  className={
                    row[header] === "Completed"
                      ? `${styles.completed} ${styles.status}`
                      : row[header] === "Waiting"
                      ? `${styles.waiting} ${styles.status}`
                      : row[header] === "Failed"
                      ? `${styles.failed} ${styles.status}`
                      : row[header] === "Select"
                      ? `${styles.yes} ${styles.status}`
                      : ""
                  }
                >
                  {row[header]}
                </Box>
              </Td>
            );
          })}
        </Tr>
      ));
  };

  const renderPagination = () => {
    const totalPages = Math.ceil(filterRows().length / perPage);
    const previousDisabled = currentPage === 1;
    const nextDisabled = currentPage === totalPages;

    return (
      <div className={styles.pagination}>
        <ButtonGroup>
          <Button
            className={styles.paginationBtn}
            onClick={() =>
              setCurrentPage(currentPage === 1 ? currentPage : currentPage - 1)
            }
            disabled={previousDisabled}
            leftIcon={<ChevronLeftIcon fontSize={"2rem"} color={"white"} />}
          ></Button>
          <Button
            className={styles.paginationBtn}
            onClick={() =>
              setCurrentPage(
                currentPage === totalPages ? currentPage : currentPage + 1
              )
            }
            disabled={nextDisabled}
            rightIcon={<ChevronRightIcon fontSize={"2rem"} color={"white"} />}
          ></Button>
        </ButtonGroup>
        <span className={styles.currentPage}>
          Page {currentPage} of {totalPages}
        </span>
        <span className={styles.itemsPerPage}>
          Items per page:
          <select
            value={perPage}
            onChange={(e) => {
              setCurrentPage(1);
              setPerPage(parseInt(e.target.value));
            }}
          >
            <option value={5}>5</option>
            <option value={10}>10</option>
            <option value={15}>15</option>
          </select>
        </span>
      </div>
    );
  };

  return (
    <Table
      className={styles.tableStyle}
      size={"sm"}
      variant={tableStyling}
      colorScheme={colorScheme}
    >
      {caption && (
        <caption>
          <div
            style={{ marginBottom: "2rem", fontWeight: "bold" }}
            className="captionStyle"
          >
            {caption}
          </div>
        </caption>
      )}
      <Thead>
        <Tr>
          {headers.map((header, index) => (
            <Th
              key={index}
              onClick={() => handleHeaderClick(header)}
              cursor={sortable ? "pointer" : "default"}
            >
              {header}
            </Th>
          ))}
        </Tr>
        <Tr>
          {headers.map((header, index) => (
            <Td key={index}>
              <Flex align="center">
                <Input
                  size="sm"
                  variant="outline"
                  placeholder={`Search ${header}`}
                  value={searchTerms[header] || ""}
                  onChange={(e) =>
                    setSearchTerms((prevSearchTerms) => ({
                      ...prevSearchTerms,
                      [header]: e.target.value,
                    }))
                  }
                  pr="2.5rem"
                />
                {/* <SearchIcon
                  boxSize={4}
                  color="gray.400"
                  position="absolute"
                  right="0.75rem"
                /> */}
              </Flex>
            </Td>
          ))}
        </Tr>
      </Thead>
      <Tbody>{renderRows()}</Tbody>
      {pagination && renderPagination()}
    </Table>
  );
};

export default DataTable;

tried creating different utils.ts file for fetching data but that does’nt work either

WordPress WPML/Enfold Theme/Avia Layout builder Javascript display error

We have a website using WordPress WPML/Enfold Theme/Avia Layout builder and AutoiFrame. The page with the error: https://www.orslabs.fr/outils/howl-mann/

The error is the code displaying below the footer. I cannot figure out how to get rid of this code populating.

I have tried to turn off header and footer in Enfold theme for this page and that does not fix the issue. This is the only page that this error code is displaying.

Please help on tracking down the source of the issue and eliminate the code displaying below the footer.

Create a copy link button in a list with unique value – PHP & JavaScript

I am writing my own WordPress plugin, which is why some of the code might look a bit weird. But my problem is with plain old PHP.

I have created a list of players that all has a unique URL. And I want to have a “copy link” button on each row/player. But I can’t seem to make this work.

I don’t want to update the site on copy, so I suppose something like Ajax needs to be used. But I have no experience.

I have tried creating it with JavaScript, but it keeps printing errors when I pass in the link (string).
It prints: “Unexpected token ‘:’. Expected ‘)’ to end an argument list.”

I have set up my PHP file like so:

<?php
// Fetching the players //

foreach($players as $player) {
    $player_email = get_post_meta($player->ID, 'email')[0];
    $player_status = get_post_meta($player->ID, 'status')[0];
    $player_link = get_permalink($player->ID);
    
    if ($player_status == 'Not completed') { array_push($not_completed_players, 'true'); }
    $return_html .= '
    <li class="players-div">
      <div class="players-text-div"> 
        <p class="players-list-p players-name"> ' . $player->post_title . ' </p>
        <p class="players-list-p players-email"> ' . $player_email . ' </p>
      </div>

      <a class="players-list-p" href="' . $player_link . '"> /' . basename($player_link) . ' </a>
      <p class="players-list-p players-email"> ' . $player_status . ' </p>

      <button type="button" onClick="copyToClipboard(' . $player_link . ')" name="copied_link" value="' . $player_link . '"> Copy link </button>
    </li>';
 }

?>

<script>
  function copyToClipboard(playerLink) {
    navigator.clipboard.writeText( playerLink );
  }
</script>

Sort table rows by drag and drop inside jquery collection

I have a problem sorting a table by drag and drop.
Let me explain:

I have an html table which is a jquery collection
this is the collection code:

$('.collection-container').collection({
min: 1,
init_with_n_elements: 1,
down: '',
up: '',
remove: '',
add: '',
elements_selector: '> tr.element',
hide_useless_buttons: false,
drag_drop: true,
drag_drop_options: {
    handle: '.sort-handle',
    sort: function() {
        $('tbody.collection-container').closest('table').css({
            opacity: 0.5
        });
        return true;
    },
    stop: function(event, ui) {
        $('tbody.collection-container').closest('table').css({
            opacity: 1
        });
        const element = ui.item;
        const nextElement = $(element).next();
        let step = 1;
        if ($(nextElement).hasClass('io-registration-form-step')) {
            if ($(nextElement).data('step') === $(element).find('input[name$="[step]"]').val()) {
                step = $(element).find('input[name$="[step]"]').val();
            } else {
                const nextStepRow = $(element).prevAll('.io-registration-form-step').last();
                if (nextStepRow.length) {
                    step = nextStepRow.data('step');
                } else {
                    step = $(element).find('input[name$="[step]"]').val();
                }
            }
        } else if (nextElement.length) {
            step = $(nextElement).find('input[name$="[step]"]').val();
        }
        $(element).find('input[name$="[step]"]').val(step);
        removeSteps();
        addSteps();
        deactivateEditors($('.element-row').first());
        activateEditors();
        return true;
    },
},
drag_drop_start: function(ui, event, elements, element) {
    return true;
},
drag_drop_update: function(ui, event, elements, element) {
    // Fired when dropping the element before stop event
    deactivateEditors($('.element-row').first());
    return true;
},
before_add: function(collection, element) {
    deactivateEditors(element);
    $(collection).closest('tbody').next().append($(collection).find('.add-fields-element-row'));
    $('tbody.collection-container').closest('table').css({
        opacity: 0.5
    });
    return true;
},
after_add: function(collection, element) {
    // Set step for new element
    var $stepElement = $(element).find('[name$="[step]"]');
    if ($stepElement.length > 0) {
        var step = $('#io-registrationform-add-to-step').val();
        $stepElement.val(step);
    }
    $(element).find('textarea.tinymce').addClass('activate-tinymce');
    activateEditors();

    $(element).find('select').select2({
        width: '100%',
        minimumResultsForSearch: 10
    });
    var $isActiveCheckbox = $(element).find('[name$="[isActive]"]');
    if ($isActiveCheckbox.length > 0) {
        $isActiveCheckbox.prop('checked', true);
        $isActiveCheckbox.on('change', checkInForm);
        $isActiveCheckbox.change();
    }

    var type = $(element).find('[name$="[_type]"]').val();

    if (type === 'registrationform_registrationformcustomfield') {
        $(element).find('select[name$="[mainGuestDisplaySetting]"]').val('3').trigger('change');
    }

    if (type === 'registrationform_registrationformsubeventselection') {
        $(element).find('select[name$="[mainGuestFormElementWidthFactor]"]').val('12').trigger('change');
        $(element).find('select[name$="[companionFormElementWidthFactor]"]').val('12').trigger('change');
        $(element).find('select[name$="[mainGuestDisplaySetting]"]').val('3').trigger('change');
        $(element).find('select[name$="[companionDisplaySetting]"]').val('0').trigger('change');
        $(element).find('input[name$="[mainGuestFormElementFullWidth]"]').prop('checked', true);
        $(element).find('input[name$="[companionFormElementFullWidth]"]').prop('checked', true);
        $(element).find('input[name$="[label]"]').focus();
    }

    $('tbody.collection-container').closest('table').css({
        opacity: 1
    });
    $(window).scrollTo(element.offset().top - 50);
    return true;
},
before_remove: function(collection, element) {
    $('tbody.collection-container').closest('table').css({
        opacity: 0.5
    });

    deactivateEditors(element);

    var key = $(element).find('input[name$="[key]"]').val();
    var stepField = $(element).find('input[name$="[step]"]');
    var labelField = $(element).find('input[name$="[label]"]');
    var typeField = $(element).find('select[name$="[type]"]');
    var optionField = $(element).find('textarea[name$="[options]"]');
    var accountLevelField = $(element).find('input[name$="[accountLevel]"]');
    var mandatoryField = $(element).find('input[name$="[mandatoryField]"]');
    var mainGuestFormElementWidthFactor = $(element).find('select[name$="[mainGuestFormElementWidthFactor]"]');
    var companionFormElementWidthFactor = $(element).find('select[name$="[companionFormElementWidthFactor]"]');
    var mainGuestDisplaySettingField = $(element).find('select[name$="[mainGuestDisplaySetting]"]');
    var companionDisplaySettingField = $(element).find('select[name$="[companionDisplaySetting]"]');
    var targetGroupField = $(element).find('select[name$="[targetGroup]"]');
    var fieldConditionField = $(element).find('input[name$="[fieldCondition]"]');

    $('#add-field-hidden option[value="' + key + '"]')
        .data('random-id', $(element).find('input[name$="[randomId]"]').val())
        .data('step', stepField.length ? stepField.val() : '1')
        .data('custom-field-id', $(element).find('input[name$="[customFieldId]"]').val())
        .data('type', typeField.length ? typeField.val() : '')
        .data('label', labelField.length ? labelField.val() : '')
        .data('options', optionField.length ? optionField.val() : '')
        .data('account-level', accountLevelField.length ? accountLevelField.is(':checked') : $(element).data('account-level'))
        .data('mandatory-field', mandatoryField.length ? mandatoryField.is(':checked') : '')
        .data('main-guest-form-element-width-factor', mainGuestFormElementWidthFactor.length ? mainGuestFormElementWidthFactor.val() : '')
        .data('companion-form-element-width-factor', companionFormElementWidthFactor.length ? companionFormElementWidthFactor.val() : '')
        .data('main-guest-display-setting', mainGuestDisplaySettingField.length ? mainGuestDisplaySettingField.val() : '')
        .data('companion-display-setting', companionDisplaySettingField.length ? companionDisplaySettingField.val() : '')
        .data('target-group', targetGroupField.length ? targetGroupField.val() : '')
        .data('field-condition', fieldConditionField.length ? fieldConditionField.val() : '');
    return true;
},
after_remove: function(collection, element) {

    activateEditors();
    $(element).find('select').select2({
        width: '100%',
        minimumResultsForSearch: 10
    });
    $('tbody.collection-container').closest('table').css({
        opacity: 1
    });
    setSelectableFields();
    return true;
},
before_up: function(collection, element) {
    $('tbody.collection-container').closest('table').css({
        opacity: 0.5
    });
    deactivateEditors($(element).prev());
    return true;
},
after_up: function(collection, element) {

    activateEditors();
    $(element).find('select').select2({
        width: '100%',
        minimumResultsForSearch: 10
    });
    $('tbody.collection-container').closest('table').css({
        opacity: 1
    });
    return true;
},
before_down: function(collection, element) {
    $('tbody.collection-container').closest('table').css({
        opacity: 0.5
    });
    deactivateEditors(element);
    return true;
},
after_down: function(collection, element) {

    activateEditors();
    $(element).find('select').select2({
        width: '100%',
        minimumResultsForSearch: 10
    });
    $('tbody.collection-container').closest('table').css({
        opacity: 1
    });
    return true;
}

});

In the table there are table rows, some of them are steps, we can know that a tr is a step if it has the class “io-registration-form-step”, and there are other table rows which are elements/fields, we can know that because they have the class “element”. I am trying to make the drag and drop work. In the collection handlers there is the stop action which will be triggered after the drop is finished. I want to be able to change the order of the fields in the same step and between the steps. Each field has a hidden field named “registrationform[elements][i][step]”.

For you to mention, I can add infinite steps and infinite elements inside steps

Let me add a screenshot of the UI:
enter image description here

On the stop handler I tried:

stop: function(event, ui) {
$('tbody.collection-container').closest('table').css({
    opacity: 1
});
const element = ui.item;
const nextElement = $(element).next();
let step = 1;
if ($(nextElement).hasClass('io-registration-form-step')) {
    if ($(nextElement).data('step') === $(element).find('input[name$="[step]"]').val()) {
        step = $(element).find('input[name$="[step]"]').val();
    } else {
        const nextStepRow = $(element).prevAll('.io-registration-form-step').last();
        if (nextStepRow.length) {
            step = nextStepRow.data('step');
        } else {
            step = $(element).find('input[name$="[step]"]').val();
        }
    }
} else if (nextElement.length) {
    step = $(nextElement).find('input[name$="[step]"]').val();
}
$(element).find('input[name$="[step]"]').val(step);
removeSteps();
addSteps();
deactivateEditors($('.element-row').first());
activateEditors();
return true;

},

CORS Alternative [closed]

I am actually building a project for my client. It’s actually a School project on react. The user has to fetch API from the backend and show the information from the APIs in the frontend. It’s being built on React.JS and TypeScript.

The issue is that the Client has gotten this project from his teacher and he does not have information about backend or APIs whatsoever he just got this project and he gave it to us as it is with the complete files. The issue is whenever I am trying to fetch the API in my Localhost server (where I am building the website) it is not fetching the API because localhost runs on HTTP and is not secured whereas the backend where the client’s APIs are stored that server is an HTTPS server and due to this issue I am unable to fetch the APIs. There will be a CORS policy which will be updated on their backend server and it will fetch the APIs, I know the solution of this problem

Now if I ask the client about the backend access he is giving me the API logins not the backend access. He is thinking of API access as the Backend access and he can not understand what I am trying to explain him. Is there any alternatives of using CORS or getting his backend? Can I do it in some other way or How can I explain him about the backend issue in simple language so it is easy for him to understand?

I am trying to get the answer if there is any alternative of CORS or if there is any way I can explain the client what the problem is and how he can get the backend access

Connection Error in MongoDB Client in VS-Code

I have installed the Node-JS environment in D-Drive of my system.
I am trying to insert/query a record in localhost MongoDB.
Since I am already using MongoDB as a Client in VS-Code, then I am assuming that I don’t need a Docker application to start a MongoDB Compass.

When I try to run the snippet, I am being encountered with the following error:

“Uncaught MongoServerSelectionError MongoServerSelectionError: connect ECONNREFUSED ::1:27017
at (file:///D:/Udemy%20Lessons/Node%20JS-%20Udemy%20Course/node_modules/mongodb/lib/sdam/topology.js:278:38)
at listOnTimeout (node:internal/timers:569:17)
at processTimers (node:internal/timers:512:7)
Process exited with code 1”.

Snippet:

`var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var query = {name: "James Chadwick"};
  dbo.collection("customers").find(query).toArray(function(err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});`

From the error, it looks like the VS-Code is not connected to the MongoDB Client, although the VS-Code console reflects the localhost:27017 as connected.
MongoDB Client in VS Code

Please let me know if I am missing any step of configuration.
Note: I have already ran “npm install mongo” command at the Terminal.

Thank you.

Trying to connect VS-Code to MongoDB Local Client on VS-Code itself.

is Fetch API supported in NextJS Api Router ( NextJS Page Router Version – 13.1.6)?

I’m newbie in NextJS and I’m curious about the usage of Fetch API in NextJS.

So I have an API handler where it does a fetch to a backend service:

  async function handler(req, res) {
    ...
    const response = await fetch('https:backend-url.com')
    ...
  }

I know that you can do a backend data fetch using getServerSideProps, which fetch is supported. However, I’m wondering if the fetch method is not supported inside an API handler router.

I’m using fetch in NextJS middleware, and that seems to work as well; it’s supported per comment I saw in another stackoverflow article.

I’m starting to suspect fetch is not supported inside the API router, as I get an error in the network request when it’s deployed.

fetch failed

I also get this error

[ERR] (node:148) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time

Locally, it works ok but when it’s deployed I get these errors.

Do I need to use node-fetch when using fetch in api routers?

Not sure what’s going, but I want to confirm if the fetch method is supported in API router.

I’ve looked in the documentation but has no mention of api router support -> https://nextjs.org/docs/architecture/supported-browsers#server-side-polyfills

Your help is appreciated, just try to learn more about NextJS

Parameterize button bind function for wechat miniprogram

I’m trying with wechat miniprogram for the first time and believe its still web pages but with its own tag (and handling).

I’m trying to do something like this:

  <view class="btns">
    <button bindtap="getWeather('New York')">New York</button>
    <button bindtap="getWeather('Toronto')">Toronto</button>
  </view>

IE for the web page buttons, I want to call the getWeather function, but different buttons will pass different parameters to the function.

How can I do it in wechat miniprogram and also html/javascript in general as well please?

UPDATE:

My code in theory should work with html/javascript in general, like:
https://www.w3schools.com/js/tryit.asp?filename=tryjs_function2

So this question only limits to wechat miniprogram then.

Scroll to a specific point

I’m trying to make an html webpage that has content above but I want the user to only be able to scroll below the content above.

I tried making the content above’s display set to none but it didn’t work.

If you don’t under stand what I mean, look at this model below

content above
content above
content above
content above
content above
PART THAT USER SEES
PART THAT USER SEES
PART THAT USER SEES
PART THAT USER SEES
PART THAT USER SEES
more stuff that user can scroll to

I want it so the user can only scroll to “more stuff that user can scroll to” and not be able to scroll to the “content above”s.

Thank you! đŸ™‚

I have a problem in my frontend under React js and openlayers Bingmap, the map does not load

The satellite map does not load while the octagon does.
I think I checked everything and I think my code is correct
this is my code :

import React, { useEffect, useState } from 'react';
import Container from '@mui/material/Container';
import logo from '../src/img/Alldem3.png';
import './AllDemande.css';
import Box from '@mui/material/Box';
import TextField from '@mui/material/TextField';
import { styled } from '@mui/system';
import VisibilityIcon from '@mui/icons-material/Visibility';
import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';
import Map from 'ol/Map';
import View from 'ol/View';
import { fromLonLat, transform } from 'ol/proj';
import LineString from 'ol/geom/LineString';
import Stroke from 'ol/style/Stroke';
import Style from 'ol/style/Style';
import TileLayer from 'ol/layer/Tile';
import BingMaps from 'ol/source/BingMaps';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import Feature from 'ol/Feature';
import 'ol/ol.css';

function AllDemande() {
  const [data, setData] = useState(null);
  const [isLoading, setIsLoading] = useState(true);
  const [searchQuery, setSearchQuery] = useState('');
  const [selectedItem, setSelectedItem] = useState(null);
  const [showForm, setShowForm] = useState(false);

  useEffect(() => {
    if (selectedItem && selectedItem.id_terrain && selectedItem.id_terrain.coordinatesText) {
      const coordinates = selectedItem.id_terrain.coordinatesText;
      const map = new Map({
        target: 'map',
        layers: [
          new TileLayer({
            source: new BingMaps({
              key: 'AopTMqA_hL6-A7_10Y_HifSekPW-cyOZXVWDB-L-GuLnf8Mw6yyMPBHRObHIZtFs',
              imagerySet: 'Aerial',
            }),
          }),
        ],
        view: new View({
          center: fromLonLat([-6.605081, 34.200794]),
          zoom: 12,
        }),
      });
  
      const coordinatesArray = coordinates
        .split('n')
        .map((coord) => coord.split(',').map(parseFloat));
  
      // Ajouter le premier point comme dernier point du tableau
      coordinatesArray.push(coordinatesArray[0]);
  
      const transformedCoordinates = coordinatesArray.map((coord) =>
        transform(coord, 'EPSG:4326', 'EPSG:3857')
      );
  
      const lineString = new LineString(transformedCoordinates);
  
      const stroke = new Stroke({
        color: 'rgba(255, 0, 0, 1)',
        width: 2,
      });
  
      const style = new Style({
        stroke,
      });
  
      const vectorLayer = new VectorLayer({
        source: new VectorSource({
          features: [
            new Feature({
              geometry: lineString,
            }),
          ],
        }),
        style: style,
      });
  
      const mapLayers = map.getLayers();
      mapLayers.clear();
      mapLayers.push(vectorLayer);
    }
  }, [selectedItem]);
  
  return (
    <>

      {showForm && selectedItem && (
        <div className="form-container">
          <Container maxWidth="sm">
            <Box
              sx={{
                bgcolor: 'White',
                padding: '30px',
                border: '1px solid gray',
                borderRadius: '8px',
                boxShadow: '0px 2px 4px rgba(0, 0, 0, 0.1)',
                position: 'absolute',
                top: '50%',
                left: '50%',
                transform: 'translate(-50%, -50%)',
                marginTop: '420px',
                width: '700px',
              }}
            >
            <GreenTop>
              <GreenHeading>Données de la demande</GreenHeading>
            </GreenTop>
              <div id="map" style={{ height: '300px', margin: '10px 0' }}></div>
              
      )}
    </>
  );
}

export default AllDemande;

a screenshot of my problem where the map does not load :

I checked everything and it looks correct to me:

  • the bingmap api key
  • the code in a new project
  • dependencies
  • imports
  • the version of ol

msal-browser error hash_does_not_contain_known_properties

i get error “hash_does_not_contain_known_properties” when login popup msal-browser

enter image description here

error occurs when logging in using a mobile browser (chrome, safari, etc)

this is my config msal enter image description here

and this is my authentication redirect uri in portal azure enter image description here

this is my url when login https://vue-msal-browser.netlify.app/#/sign-in

“@azure/msal-browser”: “^2.38.0”,
“vue”: “^3.2.13”,
“vue-router”: “^4.2.4”

Hope you can help.

Thank you

why does cypress give process is not defined error?

When i tried to run cypress code it gives me error…

I am tried to create a first test in cypress and i got :

  1. An uncaught error was detected outside of a test

0 passing (672ms)
1 failing

  1. An uncaught error was detected outside of a test:
    ReferenceError: The following error originated from your test code, not from Cypress.

process is not defined

When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.

Cypress could not associate this error to any specific test.

We dynamically generated a new test to display this failure.
at ./node_modules/ci-info/index.js (webpack:///./node_modules/ci-info/index.js:5:0)
at webpack_require (webpack:///webpack/bootstrap:19:0)
at ./node_modules/is-ci/index.js (webpack:///./node_modules/is-ci/index.js:3:17)
at webpack_require (webpack:///webpack/bootstrap:19:0)
at Object.eval (webpack:///./node_modules/cypress/lib/util.js:12:13)
at ./node_modules/cypress/lib/util.js (http://localhost:52408/__cypress/tests?p=cypress/e2e/MyFirstTest.cy.js:81000:30)
at webpack_require (webpack:///webpack/bootstrap:19:0)
at Object.eval (webpack:///./node_modules/cypress/index.js:6:13)
at ./node_modules/cypress/index.js (http://localhost:52408/__cypress/tests?p=cypress/e2e/MyFirstTest.cy.js:76837:30)
at webpack_require (webpack:///webpack/bootstrap:19:0)

vue flatpickr not showing defaultDate when there is just one enabled day

I am using ‘vue-flatpickr-component’ in my app and I have a problem with the defaultDate when I enable specific dates in its config. I have a function that fetches some values from the backend and than populates the config object.

  let config = (field)=>{
    altFormat: "d.m.y",
    altInput: true,
    dateFormat: "Y-m-d",
    allowInput: true,
    weekNumbers: false,
    disableMobile: true,
    minDate: "",
    maxDate: "",
    onClose: updateDatePicker,
    defaultDate: "",
  }if (
      searchStore.searchFieldValues[field.name] === undefined
    ) {
      searchStore.searchFieldValues[field.name] =
        utils.formatDate(tariffManagerConfig.defaultValue);
    }
    config.altFormat = tariffManagerConfig.altFormat;
   ------------------
    config.disableMobile = tariffManagerConfig.disableMobile;
    config.defaultDate = utils.formatDate(tariffManagerConfig.defaultValue);
    if (tariffManagerConfig.disable) {
      Object.assign(config, { disable: [] as any[] });
      config.disable.push(tariffManagerConfig.disable);
    }
    if (tariffManagerConfig.enable) {
      Object.assign(config, { enable: [] as any[] });
      config.enable.push(tariffManagerConfig.enable);
    }
  }
  return config;
};```

>The enable value is ["2023-08-01"], the defaultValue is "2023-08-01" and the dateFormat is 'Y-m-d'. If enable is not in the config object or if enable has a range of dates as value, the calendar starts on the defaultDate, otherwise it shows the current month. Any idea of what could cause the problem? I have tried using the Date() constructor and than initialising the hour to midnight, but it didn't work.

Firebase expressJS Authentication ( Error signing in: [t [Error]: The password is invalid or the user does not have a password.] )

i have an issue of when i want to log in a user in my Expressjs Firebase project iam getting error code from Firebase: ‘auth/wrong-password’ , i have checked every possible solution to fix this but i cant seem to figure out the issue.. my thought is that i think it has to do with hashedPassword if anyone has encountered an issue like this how did you tackle the issue.

auth.js file code:

const firebase = require('firebase/app');
require('firebase/auth');
require('firebase/firestore');
const jwt = require('jsonwebtoken');
const bcrypt = require('bcryptjs');
const cookie = require('cookie');
require('dotenv').config();

const firebaseConfig = {
  apiKey: process.env.EXPRESS_PUBLIC_FIREBASE_API_KEY,
  authDomain: process.env.EXPRESS_PUBLIC_FIREBASE_AUTH_DOMAIN,
  projectId: process.env.EXPRESS_PUBLIC_FIREBASE_PROJECT_ID,
  storageBucket: process.env.EXPRESS_PUBLIC_FIREBASE_STORAGE_BUCKET,
  messagingSenderId: process.env.EXPRESS_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
  appId: process.env.EXPRESS_PUBLIC_FIREBASE_APP_ID,
  measurementId: process.env.EXPRESS_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

firebase.initializeApp(firebaseConfig);

const db = firebase.firestore(); // Initialize Firestore

// Signing up users
const signUp = async (req, res) => {
  const { email, password, passwordRepeat } = req.body;

  if (password !== passwordRepeat) {
    return res.status(400).json({ error: 'Passwords do not match' });
  }

  try {
    // Hash the password using bcrypt
    const hashedPassword = await bcrypt.hash(password, 10);

    // Create user in Firebase Auth
    const userCredential = await firebase.auth().createUserWithEmailAndPassword(email, hashedPassword);
    const user = userCredential.user;

    // Save additional user data to Firestore
    const userData = {
      email: user.email,
      
    };
    await db.collection('users').doc(user.uid).set(userData);

    const authData = {
      hashedPassword: hashedPassword,
      
    };
    await db.collection('auth').doc(user.uid).set(authData);

    // Send token as response
    res.status(200).json({ message: 'User signed up successfully' });
  } catch (error) {
    console.error('Error signing up:', error);
    res.status(500).json({ error: 'An error occurred while signing up' });
  }
};

//Signing in users
const signIn = async (req, res) => {
  const { email, password } = req.body;
  try {
    // Retrieve user from Firebase Auth
    const userCredential = await firebase.auth().signInWithEmailAndPassword(email, password);
    const user = userCredential.user;

    // Retrieve the hashed password from the user record in Firebase
    const { hashedPassword } = await db.collection('auth').doc(user.uid).get().data();

    // Compare the hashed password using bcrypt
    const isPasswordValid = await bcrypt.compare(password, hashedPassword);
    if (!isPasswordValid) {
      res.status(401).json({ error: 'Invalid credentials' });
      return;
    }

    // Generate JWT token
    const token = jwt.sign({ uid: user.uid }, process.env.JWT_SECRET, {
      expiresIn: process.env.JWT_EXPIRESIN,
    });
    console.log("the token is " + token);

    // Set session cookie
    const cookieOptions = {
      expires: new Date(Date.now() + process.env.COOKIE_EXPIRES * 10 * 60 * 1000),
      httpOnly: true,
      secure: true,
      sameSite: 'strict',
    };
    res.setHeader('Set-Cookie', cookie.serialize('session', token, cookieOptions));

    // Send token as response
    res.status(200).json({ message: 'User signed in successfully'  });
  } catch (error) {
    console.error('Error signing in:', error);
    res.status(500).json({ error: 'An error occurred while signing in' });
  }
};

//Logging out users
const logout = async (req, res) => {
  try {
    // Clear session cookie
    const cookieOptions = {
      expires: new Date(0),
      httpOnly: true,
      secure: true,
      sameSite: 'strict',
    };
    res.setHeader('Set-Cookie', cookie.serialize('session', '', cookieOptions));

    // Sign out the current user
    await firebase.auth().signOut();
    res.status(200).json({ message: 'User signed out successfully' });
  } catch (error) {
    console.error('Error signing out:', error);
    res.status(500).json({ error: 'An error occurred while signing out' });
  }
};

module.exports = { signUp, signIn, logout };

server.js file :

// This is a Server 
const express = require("express");
const path = require("path")
const app = express();
const dotenv = require("dotenv").config();
const cookieParser = require("cookie-parser");
const { initializeApp } = require('firebase-admin/app');

app.use(express.static("public"));
app.use(express.urlencoded({ extended: false }))
app.use(express.json());
app.use(cookieParser());
app.set('view engine', 'html');

const firebaseConfig = {
    apiKey: process.env.EXPRESS_PUBLIC_FIREBASE_API_KEY,
    authDomain: process.env.EXPRESS_PUBLIC_FIREBASE_AUTH_DOMAIN,
    projectId: process.env.EXPRESS_PUBLIC_FIREBASE_PROJECT_ID,
    storageBucket: process.env.EXPRESS_PUBLIC_FIREBASE_STORAGE_BUCKET,
    messagingSenderId: process.env.EXPRESS_PUBLIC_FIREBASE_MESSAGING_SENDER_ID,
    appId: process.env.EXPRESS_PUBLIC_FIREBASE_APP_ID,
    measurementId: process.env.EXPRESS_PUBLIC_FIREBASE_MEASUREMENT_ID,
};

const webapp = initializeApp(firebaseConfig);


// Define Routes
app.use('/', require('./routes/pages'));
app.use('/auth', require('./routes/auth'));


// Start the server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

i tried to verify that the password value obtained from req.body is correct and properly passed to the createUserWithEmailAndPassword method,

Ensuring that the hashedPassword is correctly generated using bcrypt and matches the password that was used during sign-up,

Confirming that the Firestore documents for user authentication data (auth collection) and user data (users collection) are properly created and stored.

but nothing seem to work

How can I use global regex to replace all instances of something without breaking other Javascript functions?

I’m trying to replace all instances of http:/// on my website with / using global regex like this:

$('body').html($('body').html().replace(/http:////g,'/'));

It works well, but unfortunately this somehow breaks all the other Javascript-bound events and functions I have on my website.

Does someone know of a way to achieve the same without breaking the other functions?

I tried to find other ways of using global regex but I’m guessing this somehow messes with the DOM, so not sure how to fix this.

Thank you!