How can I retrive data within a function component and not in the jsx return part of the function in react?

I’m trying to retrive the firstname from the object returned in an array object from an API, its response is being loaded with axios in the userContext component and then I pass the response with the state in the variable record, so in the collectionPortfolioFollowUps I’m logging the name in the variable const userFirstName = record.firstname; however, it is returning in the console as undefinied.

Here is my code:

UserContext.jsx:

export const UserContext = createContext();

export const UserContextProvider = (props) => {
  const URL = "/api/authuser"; //http://localhost:8080

  const axiosPrivate = useAxiosPrivate();

  const initialState = {
    record: [],
  };
  const [state, dispatch] = useReducer(UserReducer, initialState);
  const getUserDetails = async (username) => {
    try {
      const response = await axiosPrivate.get(URL + "/user/" + username);
      console.log(response.data);
      dispatch({
        type: GET_RECORD,
        payload: response.data,
      });
    } catch (err) {
      console.log(err);
    }
  };
  return (
    <UserContext.Provider
      value={{
        record: state.record,
        getUserDetails,
      }}
    >
      {props.children}
    </UserContext.Provider>
  );
};

UserReducer.jsx:

import { GET_RECORD, GET_RECORD_LIST } from "../const/actionTypes";

export default (state, action) => {
  switch (action.type) {
    case GET_RECORD:
      return {
        ...state,
        record: action.payload,
      };
    default:
      return state;
  }
};

CollectionPortfolioFollowUps.jsx:

const CollectionPortfolioFollowUps = () => {
  const { getUserDetails, record } = useContext(UserContext);
  const { auth } = UseAuth();

  const extractedUsername = auth.username; // From the global auth hook, I get the logged in user from the Login component
  console.log(" Username " + extractedUsername);

  const userFirstName = record.firstname;
  console.log("User's ID" + extractedUserById);

  useEffect(() => {
    getUserDetails(extractedUsername);
  }, []);

  return <div></div>;
};

export default CollectionPortfolioFollowUps;

The menu background i want it to be 100% width with no left, right and top gaps

The menu background color should be full width, and should be full screen on 24 inch and below. Here is an image what it looks like. The website url is also in the image.

header menu image

Below is the scss where i added the background color. Please can someone edit the below code so the background colour is touching left right and top (on top there is a little gap),

.header-main-wrapper {
    max-width: 1720px;
    margin: 0 auto;
    background: #1c2e52;
    @media #{$xs,$sm,$md,$lg} {
        padding: 16px 0;

I tried using inspect in chrome but to no avail. Could not find anything on stackflow to solve it.

What RegEx would I use to parse sections of text?

I’m attempting to write a program that converts lists of terms and definitions to flashcards. My though was to use RegEx to parse the input in the following way:

term(1)-def(1)
term(2)-def(2)
term(3)-def(3)
term(4)-def(4)
term(5)-def(5)

which parses to:

terms = ["term(1)","term(2)","term(3)","term(4)","term(5)"];
definitions = ["def(1)","def(2)","def(3)","def(4)","def(5)"];

I’m very new to RegEx syntax, so I’m not sure how exactly I would do this.

Further context:

  • Each line contains this format: termdefinitionn
  • I will be writing this in JavaScript so I can host the program on a website (yes, I am aware I don’t need to use JS. It’s just the simplest to get set up).
  • The RegEx should only avoid the first -, as one might appear in the definition. - will never appear in the term.

I have a span that should show the value of the indexMatch function, but it doesn’t show what could be the error?

I have my APPS SCRIPT function which does the following: Gets the active sheet (“EPP by function”) and the data we need from it.
Looks up the row index (“rowIndex”) that corresponds to the provided lookup value (“lookupValue”) in column “C” (which contains the lookup values).
Looks up the column index (“col”) that corresponds to the provided lookup column (“searchColumn”) in row 3 (containing the column headers).
Returns “IF expected for charge” if the value in the corresponding cell is “true”, “NOT expected for charge” if the value in the corresponding cell is false (“false”), and “Missing data” or “Missing data” if the corresponding column or row is not found.

`function indexMatch(columnaBusqueda, valorBusqueda) {
  var sheet = SpreadsheetApp.getActive().getSheetByName("EPP por función");
  var data = sheet.getRange("D5:BW149").getValues();
  var lookup = sheet.getRange("C5:C149").getValues();
  var colIndex = sheet.getRange("D3:BX3").getValues()[0];
  var rowIndex = lookup.map(function(e) {return e[0];}).indexOf(valorBusqueda);
  if (rowIndex == -1) {
    return "Faltan datos";
  }
  var col = colIndex.indexOf(columnaBusqueda);
  if (col == -1) {
    return "Falta datos";
  }
  if (data[rowIndex][col] === true) {
    return "SI previsto para el cargo";
  } else if (data[rowIndex][col] === false) {
    return "NO previsto para el cargo";
  }
}`

On the other hand, in my JAVASCRIPT code it only shows me “Missing data” despite the fact that in the ID input “cargo” and input “campo8” I enter matching values ​​and they should show me in the span message “YES planned for the charge”.Please help me.

`function adicionarProduto(dados) {
  //Crea el HTML del artículo para agregar al pedido
  var div = document.createElement("div");
  div.classList.add("row");

  var divSelect = document.createElement("div");
  divSelect.classList.add("col-md-6");

  var labelSelect = document.createElement("label");
  labelSelect.textContent = dados[0].produto;

  var resultSpan = document.createElement("span");
  resultSpan.id = "result";
  resultSpan.style.color = "red";
  var resultado = ""; // Se declara la variable resultado

  var select = document.createElement("select");
  select.classList.add("form-select");
  select.id = "Campo8";

  dados.forEach((dado) => {
    var option = document.createElement("option");
    option.textContent = dado.nome;
    select.appendChild(option);

    if (dado.nome === select.value) {
      valorG = dado.valorG;
    }

    if (dado.nome === select.value) {
      resultado = dado.resultado; // Se actualiza el valor de resultado
    }
  });

  resultSpan.textContent = resultado; // Se asigna el valor de resultado al elemento resultSpan

  //Agregar elementos a div
  divSelect.appendChild(labelSelect);
  divSelect.appendChild(resultSpan);
  divSelect.appendChild(select);

  //Crea el HTML de la cantidad del artículo para agregar al pedido
  var divQuantidade = document.createElement("div");
  divQuantidade.classList.add("col-md-2");

  var labelQuantidade = document.createElement("label");
  labelQuantidade.textContent = "Cantidad";

  var stockSpan = document.createElement("span");
  stockSpan.id = "stockSpan";
  stockSpan.textContent = " S:" + valorG;
  stockSpan.style.color = "red";

  //Agrega un EventListener al elemento select que actualiza el contenido del span cada vez que cambie su valor
  select.addEventListener("change", function () {
    var nome = this.value;
    var valor = 0;
    dados.forEach((dado) => {
      if (dado.nome == nome) valor = dado.valor;
    });
    valorG = dados.find((dado) => dado.nome === nome).valorG;
    stockSpan.textContent = " S:" + valorG;

    google.script.run.withSuccessHandler(function (resultado) {
      resultSpan.textContent = resultado;
    }).indexMatch(
      document.getElementById("cargo").value,
      document.getElementById("Campo8").value
    );

    var total = inpQuantidade.value * valor;
    inpValor.value = "S/" + total.toFixed(2);
    calculaTotal();
  });

var inpQuantidade = document.createElement("input");
inpQuantidade.type = "number";
inpQuantidade.value = 1;
inpQuantidade.classList.add("form-control");

//Agrega el OnChange Event Listener donde se actualizan los valores y llama a la función computeTotal
inpQuantidade.onchange = function () {
  let div = this.parentNode;
  var nome = div.parentNode.querySelector("select").value;
  var valor = 0;
  dados.forEach((dado) => {
    if (dado.nome == nome) valor = dado.valor;
  });
  var total = this.value * valor;
  div.parentNode.querySelector('input[type="text"]').value = "S/" + total.toFixed(2);
  calculaTotal();
};

//Agregar elementos a div
divQuantidade.appendChild(labelQuantidade);
divQuantidade.appendChild(stockSpan);
divQuantidade.appendChild(inpQuantidade);

//Crea el HTML del valor del artículo para agregar al pedido
var divValor = document.createElement("div");
divValor.classList.add("col-md-3");

var labelValor = document.createElement("label");
labelValor.textContent = "Valor";

  var inpValor = document.createElement("input")
  inpValor.type = "text"
  inpValor.value = "S/"+dados[0].valor
  inpValor.classList.add("form-control")
  inpValor.classList.add("valor")

    //Agrega OnChange Event Listener donde llama a la función computeTotal
    inpValor.onchange = function(){
      calculaTotal()
    }

    //Agregar elementos a div
    divValor.appendChild(labelValor)
    divValor.appendChild(inpValor)

    //Crea el HTML del valor total del artículo para agregar al pedido
    var inpCusto = document.createElement("input")
    inpCusto.type = "number"
    inpCusto.value = dados[0].custo
    inpCusto.classList.add("custo")
    inpCusto.classList.add("displayNone")

    //Llama a la función que crea el HTML para eliminar el elemento si es necesario
    var divRemove = createDivRemove()

    //Agrega todos los divs creados al div principal del elemento
    div.appendChild(divSelect)
    div.appendChild(divQuantidade)
    div.appendChild(divValor)
    div.appendChild(inpCusto)
    div.appendChild(divRemove)

    var containers = document.querySelectorAll(".container")
    containers[1].appendChild(div)
    containers[2].classList.remove("displayNone")
    
    calculaTotal()
  }`

HTML: 
`<div class="col-md-5">
    <label>Cargo</label>
    <input class="form-control" type="text" id="cargo" name="cargo" readonly>
  </div>`

On the other hand, in my JAVASCRIPT code it only shows me “Missing data” despite the fact that in the ID input “cargo” and input “campo8” I enter matching values ​​and they should show me in the span message “YES planned for the charge”.Please help me.

HTML templating engine unable to render unicode symbols

I’m attempting to dynamically render some data on a page using nunjucks as a templating engine.

For certain parts of my data, I need unicode symbols to be rendered e.g. ✔︎

I’ve tried passing in the actual code (&#x2714;) for the symbol to my HTML template but it just renders as &#x2714; rather than the actual symbol (✔). I assume this is happening because it’s getting sent as a string.

Is there a way around this? Maybe something related to escaping characters.

I’m using JS as my server-side language.

Way to lock a pub/sub subscriber without outside scope variable in javascript?

I have this annoying problem in my codebase, let’s say I have a blackbox which is a pub/sub service, many modules can publish or subscribe.

In my particular problem I have two publish arriving very closely together and calling the same function.

So for example in pseudo code

listenerOnSomething(){
    publishToSub(1) 
}

listenerOnSomethingElse(){
   publishToSub(2)
}


// sub which is called from publishToSub
sub('subToThis'){
 publishSomethingToAnotherSub();
  or
 publishSomethingToAnotherSub();
}

In the publishSomethingToAnotherSub there are asynchronous calls to a BE endpoint which can take time. I can’t await those publishSomethingToAnotherSub calls. Which can lead to a race condition when both publishToSub are called close together. I also have no control at which time these are called.

My solution which lacks finesse is very annoying to me is the following.

export const setProgress = (progressStatus: boolean) => {
  inProgress = progressStatus;
};

let inProgress = false;

sub('subToThis'){
 await precond();
 publishSomethingToAnotherSub();
  or
 publishSomethingToAnotherSub();
}

async function precond() {
  while (inProgress) {
    await new Promise((resolve) =>
      setTimeout(async () => {
        resolve(null);
      }, 50),
    );
  }
  setHealthCheckProgress(true);
}

 //somewhere down the line call setProgress(false)

This avoids all my race condition and works perfectly but it is ugly and sad. I’ve looked at https://www.npmjs.com/package/async-mutex but it seems a bit overkill although it would definitely work. Any idea how I could upgrade this?

Thanks

Postback works once than disappears

SCENARIO:

I have a website page that has the current order of actions:

  • A repeater list (LIST 1) has buttons with OnClick calls
  • Pressing those buttons calls a code behind method and updates an Update Panel
  • The Update Panel contains another list (LIST 2) with more buttons, now with OnClientClick calls
  • Pressing a button of LIST 2 adds a new row to LIST 2

PROBLEM:

Adding a row to LIST 2 is working, but only once!
If I try to press a button of LIST 2 again, the whole div block containing the LIST 2 disappears.

CODES:

LIST 1

<asp:Repeater ID="rptProjetos" runat="server">
    <HeaderTemplate>
        <table class="table table-striped border dtInit">
            <thead>
                <tr>
                    <th>Projeto</th>
                    <th>Data Inicio</th>
                    <th>Data Término</th>
                    <th>Nº Alocados Atualmente</th>
                    <th></th>
                </tr>
            </thead>
            <tbody>
    </HeaderTemplate>
    <ItemTemplate>
                <tr>
                    <td><%# DataBinder.Eval(Container.DataItem, "Nome") %></td>
                    <td><%# DataBinder.Eval(Container.DataItem, "DataInicio", "{0: dd/MM/yyyy}") %></td>
                    <td><%# DataBinder.Eval(Container.DataItem, "DataTermino", "{0: dd/MM/yyyy}") %></td>
                    <td><%# DataBinder.Eval(Container.DataItem, "ContagemAlocados") %></td>
                    <td><asp:Button Text="Gerenciar" runat="server" ID="btnGerenciarProjeto" class="btn btn-dark"
                        CommandArgument='<%# DataBinder.Eval(Container.DataItem, "IdProjeto") %>'
                        OnClick="btnGerenciarProjeto_Click" UseSubmitBehavior="false"></asp:Button></td>
                </tr>
    </ItemTemplate>
    <FooterTemplate>
            </tbody>               
        </table>
    </FooterTemplate>
</asp:Repeater>

UPDATE PANEL

<asp:UpdatePanel runat="server" ID="updPanelTeste" UpdateMode="Conditional">
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="rptProjetos" />
    </Triggers>
    <ContentTemplate>
      ...
    </ContentTemplate>
</asp:UpdatePanel>

LIST 2

<asp:Repeater runat="server" ID="parentRepeater" OnItemCommand="parentRepeater_ItemCommand">
    <ItemTemplate>
        <div class="customFlexBox">
            <div style="<%#Eval("MarginLeftText") %>">
                <div style="<%#Eval("LeftBorder") %>">
                    <div style="<%#Eval("LeftBorderLast") %>" class="divContentHorizontal">
                        <div class="divContent">
                            <div class="divContainerBotoes">
                                <div class="botaoTooltip">
                                    <asp:Button runat="server" CssClass="buttonAcoes" Text="+" ID="btnAddLiderado"
                                        OnClientClick=<%# string.Format("test({0}, {1}); return false;", Eval("IdProjeto"), Eval("IdAssociado")) %>
                                        />
                                </div>
                            </div>
                        </div>
                    </div>
                    <asp:Repeater runat="server" ID="ChildRepeater" OnItemDataBound="mainRepeater_ItemDataBound" Visible="false">
                    </asp:Repeater>
                    <asp:Repeater runat="server" ID="NovoAvaliadoRepeater" Visible="false">
                    </asp:Repeater>
                </div>
            </div>
        </div>
    </ItemTemplate>
</asp:Repeater>

JAVASCRIPT FOR BUTTONS ON LIST 2

function test(IdProjeto, IdAssociado) {
            document.getElementById('<%=txtLiderDummy.ClientID%>').value = -1;
            document.getElementById('<%=txtLiderDummy.ClientID%>').value = IdAssociado;
            document.getElementById('<%=txtDummy.ClientID%>').value = -1;
            document.getElementById('<%=txtDummy.ClientID%>').value = IdProjeto;
            document.getElementById('<%=txtDummy.ClientID%>').trigger('OnTextChanged');
            __doPostBack("<%=updPanelTeste.UniqueID %>", "");

I tried all postback configurations and all update modes, but still the same behaviour.

Type error in Type-Script with Vue.js and Databinding

i am pretty fresh in the world of java/type script….

I want to perform a simple task, which currently costs me more than three days in development. I am even not sure why this does happen, since compiling and building are running without an error.

I am using vue.js3:

The Template with error:

<script setup lang="ts">

import type {CompanyPojo} from "@/rest/restapi-companies";
import {createNewCompany} from "@/rest/restapi-companies";

let companyPojo: CompanyPojo;

</script>


<template>

  <input id="cName" v-model="companyPojo.name" placeholder="Company Name"/>
  <label for="cName">Company Name</label>

<!--  <input id="cAddName" v-model="companyPojo.additionalName" placeholder="Company Additional Name"/>-->
<!--  <label for="cAddName">Company Additional Name</label>-->


<!--  <input id="cLegalForm" v-model="companyPojo.legalForm" placeholder="Company Legal Form"/>-->
<!--  <label for="cLegalForm">Company Legal Form</label>-->

  <button @click="createNewCompany(Object.assign(companyPojo))"> Add Company
  </button>


</template>

and this is my TypeScript-File:

export type CompanyPojo = {
    id: number;
    name: string;
    legalForm: string;
    additionalName: string;
};

export type CompanyPojoResponse = {
    data: CompanyPojo[];
};

export async function createNewCompany(newCompany: CompanyPojo) {

    try {
        const {data, status} = await axios.post<CompanyPojoResponse>('http://localhost:9050/api/v1/company/create-new', newCompany,
            {
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: 'Basic XXXXXXXXXXXXXXXXXX',
                },
            },
        );

        console.log(JSON.stringify(data, null, 4));

        // ?? "response status is: 200"
        console.log('response status is: ', status);

        return data;
    } catch (error) {
        if (axios.isAxiosError(error)) {
            console.log('error message: ', error.message);
            console.log('error message: ', error);
            return error.message;
        } else {
            console.log('unexpected error: ', error);
            return 'An unexpected error occurred';
        }
    }


}

As i imported the exported files, i expected that all those types would be availble (which there are in dev and start time).

But then, simply when opening the New-Company View, the view is empty and i see in the console this error:

TypeError: (intermediate value)(…) is undefined
setup http://localhost:9050/assets/CompanyNewView-215ff09f.js:1

Removing:

 <input id="cName" v-model="companyPojo.name" placeholder="Company Name"/>
  <label for="cName">Company Name</label>

Solves to problem.

This driving me nuts, how in the world i can bind and use those value?
I even don’t know why this is not working at all…..

react app doesn’t display pictures after being deployed on Firebase

I deployed my react app on Firebase, but none of the images are being displayed.

While creating my react app, I made sure to put all my images in the public file. One of the image path is: public/images/catalog1/Screenshot1.

After executing the npm run build, those images were copied in the folder build such as: Build/images/catalog1/Screenshot1.

After deployment, on firebase, the image file path can show as: https://my-react-app.web.app/images/catalog1/Screenshot1.jpg with a 404 error.

Or with a <img src=”data:image/png;base64,iVBORw0KGgoAAAANSUhE…….> with a long source code.

I dont know how to make my react app images to display on my firebase deployed site.

What does querySelector() do when not called on the document? [closed]

In the MDN template docs I saw code as clone.querySelectorAll("td");, so out of curiosity I wrote JS code snippet as document.querySelector(".para").append(" hello");h5.querySelector(".para").append(" world") to try to append ‘world’ to ‘hello’, but got an error.

Please explain the concept of a non-document(dot)querySelector style and its usage to rectify my error

h5=document.createElement('h5');
h5.textContent= "text updated";
h5.className= "first";
document.querySelector(".para").append(" hello");//works
h5.querySelector(".para").append(" world");//console log error of value null meaning nothing selected
<p class="para"> Test: </p>

How to set NODE_ENV so that .env.development.local is used instead of .env?

I’m having issues getting dotenv to use the .env.development.local or .env.development file when starting in development mode. It only ever uses .env.

My package.json:

{
    "name": "server",
    "version": "1.0.0",
    "description": "",
    "scripts": {
        "build": "webpack",
        "start": "nodemon src/index.js"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "devDependencies": {
        "@babel/core": "^7.21.0",
        "@babel/preset-env": "^7.20.2",
        "babel-loader": "^9.1.2",
        "copy-webpack-plugin": "^11.0.0",
        "nodemon": "^2.0.20",
        "webpack": "^5.75.0",
        "webpack-cli": "^5.0.1",
        "webpack-node-externals": "^3.0.0"
    },
    "dependencies": {
        "cors": "^2.8.5",
        "dotenv": "^16.0.3",
        "express": "^4.18.2",
        "mongoose": "^6.9.0"
    }
}

Understanding of the heirarchy is as so:

.env.development.local > .env.local > .env.development > .env

With a few additional I have omitted which I don’t plan to use.

I have been told that the issue is I need to specify the NODE_ENV somewhere in the start script but I have yet to find any documentation or guide showing me how to do that.

javascript split a string but keep the split character in the array

I have the following 2 types of lat/long strings

2154S15002E

215422N1500232E

I wish to split the string on the N or the S, the following works but it drops the N or S so I get an rp array of 2154 15002E, when i want 2154S 15002E

var rp = rPoint.split(/s*(?:N|S)s*/);

How do I split and keep the ‘S’? Or is there a better way than split?

Thank you