React map function applying CSS only some of the time

I’m writing a React component for a navbar of a personal site. I am using a list called navItems to track the name, color, and link for each navbar item:

const navItems = [
  {
    name: "home",
    color: "sky-700",
    link: "/"
  },
  {
    name: "bio",
    color: "green-500",
    link: "/bio"
  },
  {
    name: "blog",
    color: "yellow-300",
    link: "/blog"
  },
]

I then have a Navbar component to render onto the rest of the page, using navItems.map to transform the list into several Links, using a separate constant cl to construct the CSS I want for each Link:

export function Navbar() {
  return (
    <aside className="-ml-[8px] mb-16 tracking-tight">
      <div className="lg:sticky lg:top-20">
        <nav
          className="flex flex-row items-start relative px-0 pb-0 fade md:overflow-auto scroll-pr-6 md:relative"
          id="nav"
        >
          <div className="flex flex-row space-x-0 pr-10">
            {navItems.map(navItem => {
              const cl = `transition-all text-${navItem.color} flex align-middle relative py-1 px-2 m-1`

              return (
                <Link
                  key={navItem.link}
                  href={navItem.link}
                  className={cl}
                >
                  {navItem.name}
                </Link>
              )
            })}
          </div>
        </nav>
      </div>
    </aside>
  )
}

It seems to render fine, but the rendered components do not have colors displayed.

Strangely, if I add an unused constant next to cl with the name of the color attribute, it will start displaying that particular color correctly (and the rest unchanged), e.g.:

{navItems.map(navItem => {
              const unused = "text-green-500"
              const cl = `transition-all text-${navItem.color} flex align-middle relative py-1 px-2 m-1`

              return (
                <Link
                  key={navItem.link}
                  href={navItem.link}
                  className={cl}
                >
                  {navItem.name}
                </Link>
              )
            })}
...

Anyone have any idea why this is behaving like this?

Tried to populate CSS into React Links dynamically. Expected the CSS to render on the page, but it did not.

How to write common step def for Android and iOS when the locators are different for both and value is passed from feature file

I have a situation where

For example:
Android locator is having account number 6 1 8 8
iOS is having account number as 6188

All my steps are same only the account number locator is different which I am passing it from a feature file. How can I write a code which works for both.
This is because I am not hardcoding the locator in my locators java file. Am passing it from feature file.

Dynamically set the printed page size using ‘@page’

I want to print labels of 2 sizes – 3X2inches and 3x3inches.

Bydefault I have set the label print page size as 3x2inches in styles.scss (Global file).

@page {
    size: 3in 2in;
}

I now want to select the 3x3in label. After selecting the dropdown option and clicking the ‘Print’ button, how can I dynamically change the printed page size in typescript or CSS using class?

// Want to set new page size dynamically to following
@page {
    size: 3in 3in;
}

Why is the loss value of my model going up?

So I am experimenting with ml5 and sign language and right now I am trying to make a model learn off of moving signs. My code makes mediapipe collect 3780 frames, process these and save them in a variable that looks like this:

    {
      "label": "wave",
      "vector": [        
        0.7023592591285706,
        0.9515798091888428,
        (etc. (3790 in total)
      ]

I have 3 poses with about 35 examples in total. When I make ML5 train (with a neural network) my loss value appears to be going up.

Picute of my loss value in a graph

I have the following parameters to my model:
Learning rate: 0.15
epochs: 30
hidden units: 20

What is causing my learning rate to go up? Could this be the result of a small batch size?

How to pass User-Agent header to WCF Service Call(Ajax-enabled) from JavaScript

We are using an ASP.NET web application that consumes WCF service.

From javascript we are calling AjaxWebService.svc service (AJAX enabled) in following way and from AjaxWebServcice.svc we will actually call WCF service.

// CRM.js
GetAjaxService().GetUsers(function (result) {
  if (result != null) {
    // Process result
  }
});


// Infrastructure.js
function GetAjaxService() {
  if (ajaxWebService == null) {
    ajaxWebService = new AjaxWebService();
  }
  
  if (ajaxWebService == null) {
    alert('ajax service failed!!');
  }
  
  return ajaxWebService;
}

AjaxWebService.svs.cs:

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession, ConcurrencyMode = ConcurrencyMode.Multiple)]
[ServiceContract(Namespace = "", SessionMode = SessionMode.Allowed)]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]

public class AjaxWebService
{
    [OperationContract]
    public UsersData[] GetUsers()
    {
        this.Service.GetUsers();  --> calls WCF service API
    }
}

The service works fine when I call it directly, but I need to know how we can pass custom headers (e.g., the user-agent header) when using the GetAjaxService() approach.

The WCF service call works fine, but we are facing a problem. When we use fetch() or XMLHttpRequest(), I can easily pass headers (such as the User-Agent header). However, with the current GetAjaxService().GetUsers() approach, we need to know how to pass custom headers.

Any help or guidance on how to modify the GetAjaxService() call to include headers would be appreciated.

Sometime data shows in the component and sometimes dont

import getOptionsJson from "../jsonData/getOptionsJson";
import { getSelectOptions } from "../functions/apiCalls";
import { Button } from "react-bootstrap";
import { SelectComponent } from "../components/SelectComponent";

export const EditTableWithoutAdd = ({
  Group,
  handleInputChange,
  FormName,
  table_ID,
  ConditionCheck,
  errors,
  formData,
  setFormData,
  formUpdateId,
}) => {
  const [tableColumns, setTableColumns] = React.useState(Group.Component);
  const [tableData, setTableData] = React.useState([]);
  const [documentData, setDocumentData] = React.useState([]);
  const [editable, setEditable] = React.useState([]);
  const [removable, setRemovable] = React.useState([]);
  const [formDataCopy, setFormDataCopy] = React.useState({ ...formData });
  const [doctype, setDocType] = React.useState([]);
  const [docsize, setDocSize] = React.useState([]);

  const getTableStructure = (FormName, table_ID) => {
    getOptionsJson.FormName = FormName;
    getOptionsJson.table_ID = table_ID;
    getOptionsJson.session_id = JSON.parse(
      localStorage.getItem("sessionData")
    ).session_id;
    getOptionsJson.rdid = JSON.parse(
      localStorage.getItem("sessionData")
    ).session_id;
    console.log("getOptionsJson in getTableStructure", getOptionsJson);
    getSelectOptions(getOptionsJson)
      .then((data) => {
        setTableData(data.data.result[0]);
        console.log("data here in get table structure ", data);
        // return data?.result[0];
      })
      .catch((error) => {
        console.log(error);
      });
  };

  useEffect(() => {
    setEditable([]);
    setRemovable([]);
    setDocType([]);
    setDocSize([]);
    getOptionsJson.FormName = FormName;
    getOptionsJson.table_ID = table_ID;
    getOptionsJson.formupdateid = formUpdateId;
    getOptionsJson.session_id = JSON.parse(
      localStorage.getItem("sessionData")
    )?.session_id;
    getOptionsJson.rdid = JSON.parse(
      localStorage.getItem("sessionData")
    )?.session_id;
    console.log("getOptionsJson in getTableStructure", getOptionsJson);
    getTableStructure(FormName, table_ID);
  }, []);

  const initializeFormData = () => {
    // Create a copy of the current formData
    const newFormData = { ...formData };
    const newFormDataCopy = { ...formDataCopy };
    const newTableData = [...tableData]; // Create a copy of tableData
    console.log("PRINTING TABLEDATA HERE", tableData);

    // Iterate over tableData to populate formData
    newTableData.forEach((rowData, rowIndex) => {
      Object.entries(rowData).forEach(([key, value], columnIndex) => {
        if (
          key === "Editable" ||
          key === "Removable" ||
          key === "doctype" ||
          key === "docsize"
        ) {
          if (key === "docsize") {
            setDocSize((prevDocSize) => [...prevDocSize, value]);
          }
          if (key === "doctype") {
            setDocType((prevDocType) => [...prevDocType, value]);
          }
          // Skip these columns
          if (key === "Editable") {
            setEditable((prevEditable) => [...prevEditable, value]);
          }
          if (key === "Removable") {
            setRemovable((prevRemovable) => [...prevRemovable, value]);
          }
          console.log("PRINTING EDITABLE VALUE HERE", editable);
          // Skip these columns
        } else {
          tableColumns.forEach((column, headerColumnIndex) => {
            if (columnIndex === headerColumnIndex) {
              // Set the value from tableData into formData

              if (column.Component_Label) {
                // Initialize formData[Group.Group_Name] if not already
                if (!newFormData[Group.Group_Name]) {
                  newFormData[Group.Group_Name] = [];
                  newFormDataCopy[Group.Group_Name] = [];
                }
                // Initialize the specific row if not already
                if (!newFormData[Group.Group_Name][rowIndex]) {
                  newFormData[Group.Group_Name][rowIndex] = {};
                  newFormDataCopy[Group.Group_Name][rowIndex] = {};
                }

                if (column.Component_Type === "checkbox" && !value) {
                  newFormData[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = "0";
                }

                // Ensure value is a string before attempting to split
                if (typeof value === "string") {
                  const valueParts = value.split("-");

                  if (
                    valueParts.length > 1 &&
                    column.Component_Type !== "date"
                  ) {
                    // If there is a second part, store it in formData

                    newFormData[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = valueParts[1];
                    newFormDataCopy[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = valueParts[0]; // Update the first part in the tableData
                  } else {
                    const cleanedValue = typeof value === 'string' ? value.replace(/\/g, '') : value;
                  
                    newFormData[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = cleanedValue;
                    
                    newFormDataCopy[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = cleanedValue; // Update the value in the tableData
                  }
                  
                } else {
                  // If the value is not a string, store it as-is
                  const cleanedValue = typeof value === 'string' ? value.replace(/\/g, '') : value;
                  newFormData[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = cleanedValue;
                  newFormDataCopy[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = cleanedValue;
                }
              }

              if (column.Component_Type === "label") {
                console.log("logging label tags here ====", value);
              }
            }
          });
        }
      });
    });

    // Update both formData and tableData state
    setFormDataCopy(newFormDataCopy);
    setFormData(newFormData);
    // setTableData(newTableData); // Set the updated tableData
  };

  useEffect(() => {
    // initializeDocumentData();
    initializeFormData();
  }, [tableData]);

  const initializeDocumentData = () => {
    console.log("Printing tableData here in EditTableWithoutAdd", tableData);
    const newDocumentData = tableData.map((data) => ({
      Document_Type: data?.Document?.split("-")[1],
      Document_Name: data?.Document?.split("-")[0],
      doctype: data.doctype,
      docsize: data.docsize,
      doc_number: "",
    }));

    setDocumentData(newDocumentData);
  };

  const handleDocumentDataChange = (index, event) => {
    const { value } = event.target;

    // Create a new array with updated doc_number
    const updatedDocumentData = documentData.map((data, i) =>
      i === index ? { ...data, doc_number: value } : data
    );

    // Update state with new array
    setDocumentData(updatedDocumentData);
  };

  // console.log("Printing documentData here in EditTableWithoutAdd", documentData);

  console.log("Printing formData here in EditTableWithoutAdd", formData);

  console.log(
    "Printing formDataCopy here in EditTableWithoutAdd",
    formDataCopy
  );

  return (
    <>
      <h2
        style={{
          fontSize: "24px",
          textAlign: "center",
          color: "white",
          backgroundColor: "rgb(81 141 197)",
          padding: "5px",
          borderRadius: "5px",
        }}
      >
        {Group.Group_Display}
      </h2>
      <div style={{ display: "flex" }} className="grp">
        <table className="table table-border" border={2}>
          <thead>
            {tableColumns.map((column) => {
              if (
                column.Label_Display_name === "Save" ||
                column.Label_Display_name ===
                  "Document/Certificate Reference Number"
              ) {
                return null; // Skip rendering the "Save" column
              }
              return (
                <th
                  key={column.Label_Display_name}
                  border={1}
                  dangerouslySetInnerHTML={{
                    __html:
                      (column.Component_Mandatory === 1
                        ? ' <span style="color: red; background-color: #f2f2f2;">*</span>'
                        : "") + column.Label_Display_name,
                  }}
                  style={{ minWidth: "200px" }}
                />
              );
            })}
          </thead>

          <tbody>
            {formData[Group.Group_Name]?.map((rowData, rowIndex) => (
              <tr key={rowIndex}>
                {Object.entries(rowData).map(([key, value], columnIndex) => {
                  if (
                    key === "Editable" ||
                    key === "Removable" ||
                    key === "Save"
                    // key === "doctype" ||
                    // key === "docsize"
                  ) {
                    return null; // Skip rendering specific columns
                  }
                  return (
                    <td key={columnIndex}>
                      {tableColumns[columnIndex]?.Component_Type === "text" &&
                      value !== "hide" ? (
                        <input
                          className="form-control"
                          type="text"
                          value={value || ""}
                          onChange={(e) =>
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex]?.Component_Label,
                              e.target.value,
                              rowIndex,
                              "",
                              undefined,
                              undefined,
                              undefined,
                              docsize[rowIndex]
                            )
                          }
                          style={{
                            fontSize: "14px",
                            padding: "8px",
                            border: "1px solid #ccc",
                            width: "100%",
                            backgroundColor:
                                        tableColumns[columnIndex]?.Component_Read_Only
                                          ? "#f0f0f0"
                                          : "#fff",
                          color: tableColumns[columnIndex]?.Component_Read_Only
                                          ? "#a0a0a0"
                                          : "#000",
                          }}
                          placeholder={
                            tableColumns[columnIndex]?.Component_Help_Text
                          }
                          readOnly={parseInt(
                            tableColumns[columnIndex]?.Component_Read_Only
                          )}
                          
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "label" ? (
                        formDataCopy[Group.Group_Name][rowIndex][
                          tableColumns[columnIndex]?.Component_Label
                        ]
                      ) : tableColumns[columnIndex]?.Component_Type ===
                          "file" && value !== "hide" ? (
                        <>
                          <input
                            type="file"
                            className="form-control"
                            accept={doctype[rowIndex]?.split(",")}
                            onChange={(e) =>
                              handleInputChange(
                                Group.Group_Name,
                                tableColumns[columnIndex]?.Component_Label,
                                e.target.files[0],
                                rowIndex,
                                "",
                                "file",
                                undefined,
                                undefined,
                                rowData
                              )
                            }
                            style={{
                              fontSize: "14px",
                              padding: "8px",
                              border: "1px solid #ccc",
                              width: "100%",
                              backgroundColor: "#f9f9f9",
                            }}
                            // readOnly = {parseInt(editable[rowIndex])}
                          />
                          {value !== "" ? (
                            <a
                              href={`/FileViewer?fileId=${value}`}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              View
                            </a>
                          ) : null}
                        </>
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "select" ? (
                        <>
                          {/* {JSON.stringify(value)} */}
                          <SelectComponent
                            FormName={FormName}
                            table_ID={
                              tableColumns[columnIndex].Component_List_values
                            }
                            groupName={Group.Group_Name}
                            componentLabel={
                              tableColumns[columnIndex].Component_Label
                            }
                            selectedValue={value}
                            handleInputChange={handleInputChange}
                            rowIndex={rowIndex}
                            ConditionCheck={ConditionCheck}
                            readOnly={
                              tableColumns[columnIndex]?.Component_Read_Only
                            }
                          />
                          {/* {tableColumns[columnIndex]?.Component_Label === "select" && value === "hide" ? "Hide" : null} */}
                        </>
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "checkbox" ? (
                        <input
                          type="checkbox"
                          checked={parseInt(value)}
                          onChange={(e) =>
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex].Component_Label,
                              e.target.checked,
                              rowIndex
                            )
                          }
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "date" ? (
                        <input
                          type="text"
                          className="form-control"
                          value={value}
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "number" ? (
                        <input
                          className="form-control"
                          type="text"
                          value={value || ""}
                          onChange={(e) => {
                            const numericValue = e.target.value.replace(
                              /D/g,
                              ""
                            ); // Remove non-numeric characters
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex]?.Component_Label,
                              parseInt(numericValue),
                              rowIndex,
                              "",
                              undefined,
                              undefined,
                              undefined,
                              docsize[rowIndex]
                            );
                          }}
                          style={{
                            fontSize: "14px",
                            padding: "8px",
                            border: "1px solid #ccc",
                            width: "100%",
                            backgroundColor: "#f9f9f9",
                          }}
                          placeholder={
                            tableColumns[columnIndex]?.Component_Help_Text
                          }
                          readOnly={parseInt(
                            tableColumns[columnIndex]?.Component_Read_Only
                          )}
                        />
                      ) : (
                        ""
                      )}
                      {errors &&
                        errors[Group.Group_Name] &&
                        errors[Group.Group_Name][rowIndex] &&
                        errors[Group.Group_Name][rowIndex][
                          tableColumns[columnIndex]?.Component_Label
                        ] && (
                          <p
                            style={{
                              color: "red",
                            }}
                          >
                            {errors[Group.Group_Name] &&
                              errors[Group.Group_Name][rowIndex][
                                tableColumns[columnIndex]?.Component_Label
                              ]}
                          </p>
                        )}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
};

sometimes formData shows in this component and sometimes not but if I use formDataCopy it always shows data and formDataCopy is just formData. But formData is received from another parent component as a prop and I have to change formData state onChange so i want to use formData as if I use formDataCopy I am unable to update formData state in another component. One thing we can do is that change formDataCopy first and then update formDataCopy but why it is behaving like that ?

Sometime data shows in the componenta and sometimes dont

import getOptionsJson from "../jsonData/getOptionsJson";
import { getSelectOptions } from "../functions/apiCalls";
import { Button } from "react-bootstrap";
import { SelectComponent } from "../components/SelectComponent";

export const EditTableWithoutAdd = ({
  Group,
  handleInputChange,
  FormName,
  table_ID,
  ConditionCheck,
  errors,
  formData,
  setFormData,
  formUpdateId,
}) => {
  const [tableColumns, setTableColumns] = React.useState(Group.Component);
  const [tableData, setTableData] = React.useState([]);
  const [documentData, setDocumentData] = React.useState([]);
  const [editable, setEditable] = React.useState([]);
  const [removable, setRemovable] = React.useState([]);
  const [formDataCopy, setFormDataCopy] = React.useState({ ...formData });
  const [doctype, setDocType] = React.useState([]);
  const [docsize, setDocSize] = React.useState([]);

  const getTableStructure = (FormName, table_ID) => {
    getOptionsJson.FormName = FormName;
    getOptionsJson.table_ID = table_ID;
    getOptionsJson.session_id = JSON.parse(
      localStorage.getItem("sessionData")
    ).session_id;
    getOptionsJson.rdid = JSON.parse(
      localStorage.getItem("sessionData")
    ).session_id;
    console.log("getOptionsJson in getTableStructure", getOptionsJson);
    getSelectOptions(getOptionsJson)
      .then((data) => {
        setTableData(data.data.result[0]);
        console.log("data here in get table structure ", data);
        // return data?.result[0];
      })
      .catch((error) => {
        console.log(error);
      });
  };

  useEffect(() => {
    setEditable([]);
    setRemovable([]);
    setDocType([]);
    setDocSize([]);
    getOptionsJson.FormName = FormName;
    getOptionsJson.table_ID = table_ID;
    getOptionsJson.formupdateid = formUpdateId;
    getOptionsJson.session_id = JSON.parse(
      localStorage.getItem("sessionData")
    )?.session_id;
    getOptionsJson.rdid = JSON.parse(
      localStorage.getItem("sessionData")
    )?.session_id;
    console.log("getOptionsJson in getTableStructure", getOptionsJson);
    getTableStructure(FormName, table_ID);
  }, []);

  const initializeFormData = () => {
    // Create a copy of the current formData
    const newFormData = { ...formData };
    const newFormDataCopy = { ...formDataCopy };
    const newTableData = [...tableData]; // Create a copy of tableData
    console.log("PRINTING TABLEDATA HERE", tableData);

    // Iterate over tableData to populate formData
    newTableData.forEach((rowData, rowIndex) => {
      Object.entries(rowData).forEach(([key, value], columnIndex) => {
        if (
          key === "Editable" ||
          key === "Removable" ||
          key === "doctype" ||
          key === "docsize"
        ) {
          if (key === "docsize") {
            setDocSize((prevDocSize) => [...prevDocSize, value]);
          }
          if (key === "doctype") {
            setDocType((prevDocType) => [...prevDocType, value]);
          }
          // Skip these columns
          if (key === "Editable") {
            setEditable((prevEditable) => [...prevEditable, value]);
          }
          if (key === "Removable") {
            setRemovable((prevRemovable) => [...prevRemovable, value]);
          }
          console.log("PRINTING EDITABLE VALUE HERE", editable);
          // Skip these columns
        } else {
          tableColumns.forEach((column, headerColumnIndex) => {
            if (columnIndex === headerColumnIndex) {
              // Set the value from tableData into formData

              if (column.Component_Label) {
                // Initialize formData[Group.Group_Name] if not already
                if (!newFormData[Group.Group_Name]) {
                  newFormData[Group.Group_Name] = [];
                  newFormDataCopy[Group.Group_Name] = [];
                }
                // Initialize the specific row if not already
                if (!newFormData[Group.Group_Name][rowIndex]) {
                  newFormData[Group.Group_Name][rowIndex] = {};
                  newFormDataCopy[Group.Group_Name][rowIndex] = {};
                }

                if (column.Component_Type === "checkbox" && !value) {
                  newFormData[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = "0";
                }

                // Ensure value is a string before attempting to split
                if (typeof value === "string") {
                  const valueParts = value.split("-");

                  if (
                    valueParts.length > 1 &&
                    column.Component_Type !== "date"
                  ) {
                    // If there is a second part, store it in formData

                    newFormData[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = valueParts[1];
                    newFormDataCopy[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = valueParts[0]; // Update the first part in the tableData
                  } else {
                    const cleanedValue = typeof value === 'string' ? value.replace(/\/g, '') : value;
                  
                    newFormData[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = cleanedValue;
                    
                    newFormDataCopy[Group.Group_Name][rowIndex][
                      column.Component_Label
                    ] = cleanedValue; // Update the value in the tableData
                  }
                  
                } else {
                  // If the value is not a string, store it as-is
                  const cleanedValue = typeof value === 'string' ? value.replace(/\/g, '') : value;
                  newFormData[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = cleanedValue;
                  newFormDataCopy[Group.Group_Name][rowIndex][
                    column.Component_Label
                  ] = cleanedValue;
                }
              }

              if (column.Component_Type === "label") {
                console.log("logging label tags here ====", value);
              }
            }
          });
        }
      });
    });

    // Update both formData and tableData state
    setFormDataCopy(newFormDataCopy);
    setFormData(newFormData);
    // setTableData(newTableData); // Set the updated tableData
  };

  useEffect(() => {
    // initializeDocumentData();
    initializeFormData();
  }, [tableData]);

  const initializeDocumentData = () => {
    console.log("Printing tableData here in EditTableWithoutAdd", tableData);
    const newDocumentData = tableData.map((data) => ({
      Document_Type: data?.Document?.split("-")[1],
      Document_Name: data?.Document?.split("-")[0],
      doctype: data.doctype,
      docsize: data.docsize,
      doc_number: "",
    }));

    setDocumentData(newDocumentData);
  };

  const handleDocumentDataChange = (index, event) => {
    const { value } = event.target;

    // Create a new array with updated doc_number
    const updatedDocumentData = documentData.map((data, i) =>
      i === index ? { ...data, doc_number: value } : data
    );

    // Update state with new array
    setDocumentData(updatedDocumentData);
  };

  // console.log("Printing documentData here in EditTableWithoutAdd", documentData);

  console.log("Printing formData here in EditTableWithoutAdd", formData);

  console.log(
    "Printing formDataCopy here in EditTableWithoutAdd",
    formDataCopy
  );

  return (
    <>
      <h2
        style={{
          fontSize: "24px",
          textAlign: "center",
          color: "white",
          backgroundColor: "rgb(81 141 197)",
          padding: "5px",
          borderRadius: "5px",
        }}
      >
        {Group.Group_Display}
      </h2>
      <div style={{ display: "flex" }} className="grp">
        <table className="table table-border" border={2}>
          <thead>
            {tableColumns.map((column) => {
              if (
                column.Label_Display_name === "Save" ||
                column.Label_Display_name ===
                  "Document/Certificate Reference Number"
              ) {
                return null; // Skip rendering the "Save" column
              }
              return (
                <th
                  key={column.Label_Display_name}
                  border={1}
                  dangerouslySetInnerHTML={{
                    __html:
                      (column.Component_Mandatory === 1
                        ? ' <span style="color: red; background-color: #f2f2f2;">*</span>'
                        : "") + column.Label_Display_name,
                  }}
                  style={{ minWidth: "200px" }}
                />
              );
            })}
          </thead>

          <tbody>
            {formData[Group.Group_Name]?.map((rowData, rowIndex) => (
              <tr key={rowIndex}>
                {Object.entries(rowData).map(([key, value], columnIndex) => {
                  if (
                    key === "Editable" ||
                    key === "Removable" ||
                    key === "Save"
                    // key === "doctype" ||
                    // key === "docsize"
                  ) {
                    return null; // Skip rendering specific columns
                  }
                  return (
                    <td key={columnIndex}>
                      {tableColumns[columnIndex]?.Component_Type === "text" &&
                      value !== "hide" ? (
                        <input
                          className="form-control"
                          type="text"
                          value={value || ""}
                          onChange={(e) =>
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex]?.Component_Label,
                              e.target.value,
                              rowIndex,
                              "",
                              undefined,
                              undefined,
                              undefined,
                              docsize[rowIndex]
                            )
                          }
                          style={{
                            fontSize: "14px",
                            padding: "8px",
                            border: "1px solid #ccc",
                            width: "100%",
                            backgroundColor:
                                        tableColumns[columnIndex]?.Component_Read_Only
                                          ? "#f0f0f0"
                                          : "#fff",
                          color: tableColumns[columnIndex]?.Component_Read_Only
                                          ? "#a0a0a0"
                                          : "#000",
                          }}
                          placeholder={
                            tableColumns[columnIndex]?.Component_Help_Text
                          }
                          readOnly={parseInt(
                            tableColumns[columnIndex]?.Component_Read_Only
                          )}
                          
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "label" ? (
                        formDataCopy[Group.Group_Name][rowIndex][
                          tableColumns[columnIndex]?.Component_Label
                        ]
                      ) : tableColumns[columnIndex]?.Component_Type ===
                          "file" && value !== "hide" ? (
                        <>
                          <input
                            type="file"
                            className="form-control"
                            accept={doctype[rowIndex]?.split(",")}
                            onChange={(e) =>
                              handleInputChange(
                                Group.Group_Name,
                                tableColumns[columnIndex]?.Component_Label,
                                e.target.files[0],
                                rowIndex,
                                "",
                                "file",
                                undefined,
                                undefined,
                                rowData
                              )
                            }
                            style={{
                              fontSize: "14px",
                              padding: "8px",
                              border: "1px solid #ccc",
                              width: "100%",
                              backgroundColor: "#f9f9f9",
                            }}
                            // readOnly = {parseInt(editable[rowIndex])}
                          />
                          {value !== "" ? (
                            <a
                              href={`/FileViewer?fileId=${value}`}
                              target="_blank"
                              rel="noopener noreferrer"
                            >
                              View
                            </a>
                          ) : null}
                        </>
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "select" ? (
                        <>
                          {/* {JSON.stringify(value)} */}
                          <SelectComponent
                            FormName={FormName}
                            table_ID={
                              tableColumns[columnIndex].Component_List_values
                            }
                            groupName={Group.Group_Name}
                            componentLabel={
                              tableColumns[columnIndex].Component_Label
                            }
                            selectedValue={value}
                            handleInputChange={handleInputChange}
                            rowIndex={rowIndex}
                            ConditionCheck={ConditionCheck}
                            readOnly={
                              tableColumns[columnIndex]?.Component_Read_Only
                            }
                          />
                          {/* {tableColumns[columnIndex]?.Component_Label === "select" && value === "hide" ? "Hide" : null} */}
                        </>
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "checkbox" ? (
                        <input
                          type="checkbox"
                          checked={parseInt(value)}
                          onChange={(e) =>
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex].Component_Label,
                              e.target.checked,
                              rowIndex
                            )
                          }
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "date" ? (
                        <input
                          type="text"
                          className="form-control"
                          value={value}
                        />
                      ) : tableColumns[columnIndex]?.Component_Type ===
                        "number" ? (
                        <input
                          className="form-control"
                          type="text"
                          value={value || ""}
                          onChange={(e) => {
                            const numericValue = e.target.value.replace(
                              /D/g,
                              ""
                            ); // Remove non-numeric characters
                            handleInputChange(
                              Group.Group_Name,
                              tableColumns[columnIndex]?.Component_Label,
                              parseInt(numericValue),
                              rowIndex,
                              "",
                              undefined,
                              undefined,
                              undefined,
                              docsize[rowIndex]
                            );
                          }}
                          style={{
                            fontSize: "14px",
                            padding: "8px",
                            border: "1px solid #ccc",
                            width: "100%",
                            backgroundColor: "#f9f9f9",
                          }}
                          placeholder={
                            tableColumns[columnIndex]?.Component_Help_Text
                          }
                          readOnly={parseInt(
                            tableColumns[columnIndex]?.Component_Read_Only
                          )}
                        />
                      ) : (
                        ""
                      )}
                      {errors &&
                        errors[Group.Group_Name] &&
                        errors[Group.Group_Name][rowIndex] &&
                        errors[Group.Group_Name][rowIndex][
                          tableColumns[columnIndex]?.Component_Label
                        ] && (
                          <p
                            style={{
                              color: "red",
                            }}
                          >
                            {errors[Group.Group_Name] &&
                              errors[Group.Group_Name][rowIndex][
                                tableColumns[columnIndex]?.Component_Label
                              ]}
                          </p>
                        )}
                    </td>
                  );
                })}
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </>
  );
};

sometimes formData shows in this component and sometimes not but if I use formDataCopy it always shows data and formDataCopy is just formData. But formData is received from another parent component as a prop and I have to change formData state onChange so i want to use formData as if I use formDataCopy I am unable to update formData state in another component. One thing we can do is that change formDataCopy first and then update formDataCopy but why it is behaving like that ?

Issue with Dynamic Importing of Svelte Component in JavaScript with Svelte

I’m trying to dynamically import a Svelte component in my project, but I’m encountering a TypeError when including the file extension in the variable that holds the component name.

Here is the working example:

const componentName = "MyComponent";
let importedComponent = (await import(`$myGlobalComponentFolder/myComponent/${componentName}.svelte`)).default;

This code works perfectly fine and successfully imports the component.

However, when I change the code like this (only the file extension is moved):

const componentName = "MyComponent.svelte";
let importedComponent = (await import(`$myGlobalComponentFolder/myComponent/${componentName}`)).default;

I receive the following error:

TypeError: Failed to resolve module specifier '$myGlobalComponentFolder/myComponent/MyComponent.svelte'

Why does the first import work while the second one fails? The logged component path is in both scenarios the same and valid.

Serialise HTML Form with time/text input type and validation of time fields

I am trying to create an HTML form that will be used to send data to the backend in C#.

Below is the form which consists of 2 fields: FROMTIME and TOTIME. I need to make sure that the user inputs the values in the format of HH:MM but this is not feasible without validation.

I have tried using input type="time" but this does not allow me to serialise the data and send them to the backend. I am using $("#editForm").serialize or $("#editForm").serializeObject or $("#editForm").serializeArray but the data is empty because the serialisation does not include the Time data. Any ideas please?

Could you please let me know, is there an easy way to force the user to input hour and minutes in the format of HH:MM? Many thanks!

<form id="editForm">
  <table>
    <tr>
      <th>From Time: </th>
      <td style="background-color:white;">       
        <input  type="text" id="FROMTIME"  placeholder="HH:MM" name="FROMTIME" value="@Model.FROMTIME" asp-for="FROMTIME" required form="editForm" />
      </td>
    </tr>
    <tr>
      <th>To Time: </th>
      <td style="background-color:white;">
        <input type="text" id="TOTIME"  placeholder="HH:MM" name="TOTIME" value="@Model.TOTIME" asp-for="TOTIME" required form="editForm" />
      </td>
    </tr>
  </table>
</form>

Why am I getting a customer is not defined error? [closed]

I am currently creating a sign-in page where the customer can sign in using their username and password.

I have two files, sign-in.html and sign-in.js. I believe that the html file is working well and there is no problems with it.

    <main>
        <navmenu></navmenu>
        <h2>Sign In</h2>
        <form @submit.prevent="signIn()">
            <label>Username:</label>
            <input type="text" id="username" v-model="customer.username" required><br /><br />
            <label>Password:</label>
            <input type="password" id="password" v-model="customer.password" required><br /><br />
            <button type="submit">Sign In</button>
        </form>
        <p>If you don't have an account, <a href="create-account.html">sign up here</a>.</p>
    </main>
    <script type="module" src="js/view-products.js"></script>
</body>
</html>

The problem lies in the js file.

import { navigationMenu } from './navigation-menu.js';
import { sessionStore } from './session-store.js';
const app = Vue.createApp({
    data() {
        return {
            customer: {
                username: '',
                password: ''
            }
        };
    },
    methods: {
        signIn() {
            alert('Sign In method called!');
            axios.post('/api/customers/' + this.customer.username, {
                password: this.customer.password
            })
            .then(response => {
                alert('Sign in successful!');
                window.location = 'view-products.html';
            })

        }
    },

I know the html works well as when I remove the customer.username and customer.password to just username and password it appears, but when i have the customer. in front of it, it no longer shows and I get a blank page. I also get an error which says customer is not defined.

This makes me think that the problem is the data customer in the js file but everything else I have tried has not worked.

Is my code correct or could the problem be from another file in my program.

When I added some debugging to my code to see the problem it just wouldn’t run that file, it wouldn’t give me an error either it was just simply providing a blank page without even using the navigation bar which would have no effect on the customer. things.

The full error message from the console of the page was:
“Uncaught TypeError: customer is undefined”

HTML redirects not working using this sandbox code

Trying to create a sandbox for simulating a bunch of html files, (some of which are nested within others in this format for example

function redirectToProcessor(event) {
            event.preventDefault();
            window.location.href = 'video-processor.html';
        }

But when using the html code below (the sandbox’s code), its only rendering one page and not redirecting when the right buttons are clicked. Tried everything, if someone can figure out what I am doing wrong that will be very helpful. The above code is part of the html files I tried to use with it, but it just isn’t working.

For it to be able to simulate htmls even with redirects, no redirects happening.

const fileList = document.getElementById('fileList');
const fileInput = document.getElementById('fileInput');
const tabs = document.getElementById('tabs');
const codeArea = document.getElementById('codeArea');
const previewFrame = document.getElementById('previewFrame');

let files = {};
let currentFile = null;

fileInput.addEventListener('change', (event) => {
  const newFiles = event.target.files;
  for (let file of newFiles) {
    const reader = new FileReader();
    reader.onload = (e) => {
      files[file.name] = e.target.result;
      updateFileList();
      createTab(file.name);
    };
    reader.readAsText(file);
  }
});

function updateFileList() {
  fileList.innerHTML = '';
  for (let fileName in files) {
    const li = document.createElement('li');
    li.textContent = fileName;
    li.onclick = () => openFile(fileName);
    fileList.appendChild(li);
  }
}

function createTab(fileName) {
  const tab = document.createElement('div');
  tab.className = 'tab';
  tab.textContent = fileName;
  tab.onclick = () => openFile(fileName);
  tabs.appendChild(tab);
}

function openFile(fileName) {
  currentFile = fileName;
  codeArea.value = files[fileName];
  updateTabs();
  updatePreview(fileName);
  history.pushState({
    file: fileName
  }, '', `#${fileName}`);
}

function updateTabs() {
  Array.from(tabs.children).forEach(tab => {
    tab.classList.toggle('active', tab.textContent === currentFile);
  });
}

function updatePreview(fileName) {
  const blob = new Blob([files[fileName]], {
    type: 'text/html'
  });
  const url = URL.createObjectURL(blob);
  previewFrame.src = url;
}

codeArea.addEventListener('input', () => {
  if (currentFile) {
    files[currentFile] = codeArea.value;
    updatePreview(currentFile);
  }
});

previewFrame.addEventListener('load', () => {
  const iframeWindow = previewFrame.contentWindow;
  iframeWindow.addEventListener('click', handleIframeClick);

  // Override the window.location object in the iframe
  Object.defineProperty(iframeWindow, 'location', {
    set: function(value) {
      if (typeof value === 'string') {
        navigateTo(value);
      } else if (value && typeof value.href === 'string') {
        navigateTo(value.href);
      }
    },
    get: function() {
      return {
        href: currentFile,
        assign: function(url) {
          navigateTo(url);
        },
        replace: function(url) {
          navigateTo(url);
        }
      };
    }
  });

  // Override history methods
  iframeWindow.history.pushState = function(state, title, url) {
    navigateTo(url);
  };
  iframeWindow.history.replaceState = function(state, title, url) {
    navigateTo(url);
  };
});

function handleIframeClick(event) {
  if (event.target.tagName === 'A') {
    event.preventDefault();
    const href = event.target.getAttribute('href');
    navigateTo(href);
  } else if (event.target.tagName === 'BUTTON' || event.target.tagName === 'INPUT') {
    const clickEvent = new MouseEvent('click', {
      bubbles: true,
      cancelable: true,
      view: previewFrame.contentWindow
    });
    event.target.dispatchEvent(clickEvent);
  }
}

function navigateTo(path) {
  // Handle relative paths
  if (!path.startsWith('/') && !path.startsWith('http')) {
    const currentDir = currentFile.split('/').slice(0, -1).join('/');
    path = `${currentDir}/${path}`;
  }

  // Normalize path
  path = path.replace(//.//g, '/').replace(//[^/]+/..//g, '/');

  if (files[path]) {
    openFile(path);
  } else if (path.startsWith('http')) {
    console.log(`External URL: ${path}`);
    // Handle external URLs as needed
  } else {
    console.error(`File not found: ${path}`);
  }
}

window.addEventListener('popstate', function(event) {
  if (event.state && event.state.file) {
    openFile(event.state.file);
  } else {
    const fileName = window.location.hash.slice(1);
    if (files[fileName]) {
      openFile(fileName);
    }
  }
});

// Initialize with index.html if it exists
if (files['index.html']) {
  openFile('index.html');
}
<div class="container">
  <div class="file-explorer">
    <h3>Files</h3>
    <ul id="fileList"></ul>
    <input type="file" id="fileInput" multiple>
  </div>
  <div class="editor">
    <div class="tabs" id="tabs"></div>
    <textarea class="code-area" id="codeArea"></textarea>
  </div>
  <iframe class="preview" id="previewFrame" src="about:blank"></iframe>
</div>

Is there a solution to export a Plotly graph (in React) to both image and PDF?

Per Plotly documentation, we can natively export a graph to several image format (png, svg, jpeg or webp). Other libraries, like React-pdf, allow to export a PDF file from a React component. I’d like to be able to let my users export a displayed Plotly graph in either image or PDF with a custom input.

Is there any clean solution to do this or should I play with the DOM to hide both libraries behind my custom input ?

Reactjs modal bug – doesn’t close on 2nd open

reactjs bug — I have a node api and react shell and I am running into some bugs I am having difficulty in figuring out how to fix.

Its likely the way I am managing the props/changes between parents/child and other components is playing havoc

enter image description here

+user editing on admin page – there is a bug here (props changing issue)
^ so its again maybe a props/prev – child/parent issue — where I want the modal to close – it seemed to jam up – as if it was unsure if it was open or closed..

so I first click on edit user – their details come up, I make a change – submit, saves and closes the modal fine, but if I do it again – submit, saves the changes but does not close the modal – it remains open..

So here is the modal box part on the admin page — there is one for adding a new user and editing an existing user. The modal breaks when trying to close it after its been opened –

  getEditUser(item){
    //console.log("EDIT", item);
    let that = this;

    return (
      <ModalBox 
        open={that.state.openEdit}
        handleOpen={function(data){
          //console.log("that.state.openEdit", that.state.openEdit)
          //console.log("OPEN EDIT PANEL");
          that.setState({ 
            openEdit: true, 
          });
        }}
        handleClose={function(data){
          //console.log("that.state.openEdit", that.state.openEdit)
          //console.log("CLOSE EDIT PANEL");
          that.setState({ 
            openEdit: false, 
          });
        }}
        button={{"label": "Edit", "color":"primary", "variant":"contained"}}
        modalContents={
          <div className="standard-padding edit-user">
            <h5>Edit User {item.id}</h5>
      
            <GeneralFormik 
              schema={this.getSchema(item)} 
              submitHandler={this.editUserHandler}
              returnAsFormData={true}
            />
                    
          </div>
        }
      />
    )

  }

when the edit has been submitted – want to close the modal automatically

  editUserHandler(data){
    let that = this;

    const formObject = Object.fromEntries(data.entries())
    
    //console.log("CLOSE EDIT PANEL");
    that.setState({ 
      openEdit: false, 
    });

    this.props.editUser(formObject.id, data, getToken(), function(resp) {
      if(resp){
        //console.log("resp-readUsers", resp.data);
        //console.log("resp-user", resp.data.data.person);
        console.log("RESP--------", resp)
        that.fetchUsers();
      }
    });
  }

here is the modal box code

import React, { Component } from 'react';

import Modal from '@mui/material/Modal';
import Backdrop from '@mui/material/Backdrop';
import Fade from '@mui/material/Fade';
import Button from '@mui/material/Button';

import IconButton from '@mui/material/IconButton';
import CloseIcon from '@mui/icons-material/Close';

import './ModalBox.scss';

class ModalBox extends Component {
    constructor(props, context) {
      super(props, context);
      this.state = { open: false };
    }

    componentDidUpdate(prevProps) {
      //Typical usage to compare props     
      if(this.props.open !== prevProps.open) {
        if(this.props.open){
          this.handleOpen();
        } else{
          this.handleClose();
        }
      }
    }

    handleOpen = () => {
      this.setState({open: true});

      //if there is a handle open callback - invoke it
      if(this.props.handleOpen) {
        this.props.handleOpen();
      }
    };

    handleClose = () => {
      this.setState({open: false});

      //if there is a handle close callback - invoke it
      if(this.props.handleClose) {
        this.props.handleClose();
      }
    };

    bodyClick = (el) => {
      if(el.target.dataset){
        let dismiss = el.target.dataset.dismiss;

        if(dismiss === "modal"){
          this.handleClose();
        }
      }
    }

    render() {
      return (
        <>
          {this.props.button &&
            (
              <Button 
                variant={this.props.button.variant}
                color={this.props.button.color} 
                onClick={this.handleOpen}
              >
                {this.props.button.label}
              </Button>
            )
          }
          <Modal
            aria-labelledby="transition-modal-title"
            aria-describedby="transition-modal-description"
            className={'modalbox'}
            open={this.state.open}
            onClose={this.handleClose}
            closeAfterTransition
            BackdropComponent={Backdrop}
            BackdropProps={{
              timeout: 500,
            }}
          >
            <Fade in={this.state.open}>
              <div className={'App modalboxform wide-modal'} onClick={this.bodyClick}>
                <IconButton className="close-button" onClick={this.handleClose}>
                  <CloseIcon/>
                </IconButton>

                <div className="modalboxwrap">
                  {this.props.modalContents}
                </div>
              </div>
            </Fade>
          </Modal>
        </>
      );
    }
}

export default ModalBox;

Logout the user when browser tab/window is closed but not on refresh

In one of my angular project i’m facing a problem where user is getting logged out when browser is refreshed but i need to logout user only when browser tab/window is closed. Though i’m able to logout the user whenever browser window/tab is closed but same logout api call is made whenever i’m refreshing the browser.

Is there any way to differentiate between the browser refresh and browser close ? Or is there any way to call logout api only when tab/window is closed ?

Any help on this is highly appreciated. Thanks in advance.

I tried native javascript’s beforeunload event to logout the user whenever tab is closed but same logout api is being called whenever i’m refreshing the browser. My expectation is to logout user only when tab/window is closed.

How to get referenced auth.user data from my teams table

I created a teams table in supabase and it has a column name created_by which is a foreign key referencing auth.user. How can i write a javascript client query to get all the team members with
created_by populated in it.

This is my code that i am using to get teams with its creator data.

const response = await supabase
.from(“team”)
.select(
id, name, members, created_by, auth.users (id, email, full_name, profile_picture), workspace_id
)