How to add form elements to Dialog in Dojo dynamically

Please give me a code example on how to dynamically add any form elements to Dialog.

var myDialog = new Dialog({
    title: "Edit form",
    style: "width: 300px; height: 200px"
});
myDialog.show();

It seems I figured it out a little, but I need to somehow wrap the elements in a div since they go in the Dialog box in one line, I don’t know how to do this

var form = new Form();

var myDialog = new Dialog({
    content: form,
    title: "Dialog Box",
    style: "width: 300px; height: 200px"
});

new Select({
    name: "select2",
    options: [
        { label: "Item1", value: "1" },
        { label: "Item2", value: "2" },
        { label: "Item3", value: "3" }
    ]
}).placeAt(form.containerNode);

Cloud Application Programming Model OData v2 proxy

I am running a cap backend application with express.js and want to access the odata services with v2. In this project I used the @sap/cds-odata-v2-adapter-proxy which is now deprecated.
The recommended package is now @sap-js-community/odata-v2-adapter.

I tried to implement the proxy in the same way as the deprecated proxy. It did not work and I did not get any error messages.

This is my server.js

const express = require('express');
const proxy = require('@sap-js-community/odata-v2-adapter');
const cds = require('@sap/cds');
const app = express();

app.use(proxy());
app.use(bodyParser.json());

(async () => {
  await cds.serve('TestService').in(app).at('/test');

  app.listen(process.env.PORT || 4004);
})(); 

In React native, OnOpenWindow webview property is not triggering or working

In React Native, OnOpenWindow webview property is not triggering or listening when my webview source URI link have additonal query parameter.

not-working

In this stage onOpenwindow property is not triggering due to source URI link has additonal query params

<WebView

      source={{ uri: `https://example.com/?apk=1` }
          onOpenWindow={(syntenticEvent) => {
            const { nativeEvent } = syntenticEvent;
            const { targetUrl } = nativeEvent;
            console.log("target url of opened popup:::::::", targetUrl);

}
/>

working

<WebView

      source={{ uri: `https://example.com` }
          onOpenWindow={(syntenticEvent) => {
            const { nativeEvent } = syntenticEvent;
            const { targetUrl } = nativeEvent;
            console.log("target url of opened popup:::::::", targetUrl);

}
/>

javascript document.querySelector null = error / breaks other javascript [duplicate]

my javascript =

document.querySelector('#plus').addEventListener('click', () =>
tlshowhide.reversed() ? tlshowhide.play() : tlshowhide.reverse() );

Where my page has the #plus element this works fine but if the page does not have the #plus element then the console shows an error

 document.querySelector(...) is null

and other unrelated javascript breaks.

So is it expected that document.querySelector being null is an error that breaks other javascript, and if so how can I rewrite my javascript to say “if the element X is found on the page do Y, and if element X is not found on the page then don’t worry about it, just move on”?

Videos Stop Autoplaying After Navigating Away – Barbajs

I am using barba.js for page transitions. I have video element on my corporate page that are set to autoplay, loop, and muted. Work well when I initially load the corporate page. However, when I navigate away from the corporate page and then return (without refreshing the page), the video is no longer autoplaying. The video only start autoplaying again if I manually reload the page. Note: I’m not using any frameworks (like React, Vue, etc.), just plain JavaScript (vanilla JS).

 <video loop muted autoplay>
         <source src="VIDEO_LINK" type="video/mp4">
 </video>

I re-run all my JavaScript code on every page transition with Barba.js. What should i do for the video element ?

How I can ensure the video continue autoplaying when navigating back to the page, without requiring a page reload?

Thanks in advance!

How to mock a dependency of a dynamically imported module in jest

module-a.js

class Math {
  pi() {
    return 3.14;
  }
}

export default Math

module-b.js

import Math from './module-a';

const piVal = Math.pi();

export const doSomeCalc = (a) => {
  return piVal + a;
}

module-b.test.js

describe('module b', () => {
    it('should return correct value', () => {
        // I want to mock the return value of pi() here
        return import('./module-b').then(module => {
          expect(
            module.doSomeCalc(20)
          ).toBe(23.14);
        });
    });
})

How do I mock Math.pi() here?

I need to import the module dynamically as Math.pi() is evaluated as soon as I import the module.

Can not set httponly cookie using FastAPI

When user Log In I am creating Login using pyjwt and setting Httponly cookie but not able to set the cookie because of CROS.

When user Log In I am creating Login using pyjwt and setting httponly cookie like this.

def create_jwt(user_id: str, ip_address: str=None):
    payload = {
        "sub": str(user_id),
        "ip": ip_address,
        "iat": datetime.now(),
        "exp": datetime.now() + timedelta(minutes=30)
    }

    return jwt.encode(payload, PRIVATE_KEY, algorithm="RS256)
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
database = self.client["test"]
@login_router.post("/login", response_model=SuccessResponse, tags=("Login",))
async def login(request: LoginRequest, response: Response):
    try:
        username = request.username
        password = request.password

        user = database.find_one(
            "user",
            filter={"username": username},
        )

        if not user or not login_instance.verify_password(
            password, user.get("password"), user.get("salt")
        ):
            raise InvalidUser()

        from ..authentication import create_jwt

        response.set_cookie(
            key="access_token",
            value=create_jwt(username),
            httponly=True,
            samesite="None",
            secure=False,
            path="/",
        )

        response_content = {
            "status": status.HTTP_200_OK,
            "success": True,
            "message": "User Logged In successfully",
            "data": {},
        }
        return response_content
    except InvalidUser:
        raise InvalidUser()
    except Exception as e:
        raise InternalServerError(e)

When i hit this API in frontend (my frontend is written in VueJS) it is saying not able to set the cookie.
Error Image

I have add CROS in FastAPI main.py
main.py

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["http://localhost:8081"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

My front end is running on port **8081.

Frontend**
api.js

import axios from 'axios';

const apiURL = process.env.VUE_APP_BASE_URL;

const apiClient = axios.create({
    baseURL: apiURL,
    headers: {
        'Content-Type': 'application/json',
    },
    withCredentials: true,
});

export const get = (endpoint, params = {}) => {
    return apiClient.get(endpoint, { params });
};

export const post = (endpoint, payload) => {
    return apiClient.post(endpoint, payload);
};

Unable to show mat-icon while updating data in Autocomplete in Angular UI

I have an autocomplete input field where I am showing the data and the user can select the data and submit it. each data has an icon attached – highlight_off which is used for deleting the data, if the user selects a date from the drop-down then a checkbox is attached to the data so that the user cannot delete it until and unless removed from the input box.

Image for reference when we populate the data –

data-populated

When we select the data then this close button turns into a checkbox to show as selected data (internal functionality of angular UI library)

data selected

Now the issue is when we select the data add a word to it and remove it immediately then icon disappears neither checkbox nor the highlight_off icon is showing which seems very strange
enter image description here

How will we show the icon if we edit the data, the issue is when we add something extra and remove from selected data, because when we directly start removing the selected data words then the icon highlight_off is showing which is correct but if we add a word and remove from selected data then this issue arise.

Code –

HTML

    <div class="tw-w-2/5">
          <mat-form-field
            appearance="outline"
            requiredInput
            class="portAutocomplete tw-w-full">
            <mat-label>{{ 'COMPANY-NAME' | translate }}</mat-label>
            <input
              matInput
              appInputRestriction
              [matAutocomplete]="autoCompnay"
              appTabNavigation
              appExtMatAutocompleteTriggerEnforceSelection
              formControlName="cCompanyName"
              autocomplete="off" />
            <button
              type="button"
              mat-icon-button
              matSuffix
              tabindex="-1"
              (click)="clearCompanyName()"
              *ngIf="pickupForm.get('cCompanyName')?.value">
              <mat-icon>close</mat-icon>
            </button>
            <mat-autocomplete
              #autoCompnay="matAutocomplete"
              (optionSelected)="updateOtherInput($event.option.value)"
              [displayWith]="displayCompnayname.bind(this)">
              <mat-option
                *ngFor="let PickupAddress of filteredPickupAddress | async"
                [value]="PickupAddress.cCompanyName">
              <div class="tw-flex tw-justify-between tw-items-center">
                <small class="pickup-width">{{ PickupAddress.cCompanyName | titlecase }}</small>
                <button
                *ngIf="!shouldHideIcon(PickupAddress.cCompanyName)"
                mat-icon-button
                matTooltip="Delete Pickup Details"
                (click)="openDeleteConfirmationDialog(PickupAddress)"
                tabindex="-1"
              >
                <mat-icon style="color: #D70700;">highlight_off</mat-icon>
              </button>
            </div>
              </mat-option>
            </mat-autocomplete>
            <mat-error
              *ngIf="pickupForm?.get('cCompanyName')?.hasError('maxlength')">
              {{ 'VALIDATION.COMMON-MESSAGES.MAX-40-CHAR-LENGTH' | translate }}
            </mat-error>
          </mat-form-field>
        </div> 

TS

      @ViewChild('autoCompnay') autoCompnay!: MatAutocomplete;
  selectedCompanyName: string | null = null;
 
  ngOnInit() {

//some code
}

 displayCompnayname(Value: any) {
    let filterValue = _.findWhere(this.listPickupAddress, {
      cCompanyName: Value,
    });
    return !_.isUndefined(filterValue) ? filterValue.cCompanyName : '';
  }

  async updateOtherInput(data: any) {
    this.selectedCompanyName = data;
    let pickupData = this.pickupForm.value;
    let filterValue = _.findWhere(this.listPickupAddress, {
      cCompanyName: data,
    });

    let pickupFormPatchValue = await this.setRatedBookingLogic(filterValue);
    this.pickupForm.patchValue(pickupFormPatchValue);
    this.pickupForm.get('cContactName')?.setValue(filterValue.cContactName);
    this.pickupForm.get('cAddress')?.setValue(filterValue.cAddressLine1);
    if (this.cCityName === '') {
      this.pickupForm.get('cCity')?.setValue(filterValue.cCityName);
    }
    if (this.cPostalcode === '') {
      this.pickupForm.get('cPostalcode')?.setValue(filterValue.cPostalCode);
    }
    if (this.cState === '') {
      this.pickupForm.get('cState')?.setValue(filterValue.cStateName);
    }
    if (this.cCountry === '') {
      this.pickupForm.get('cCountry')?.setValue(filterValue.cCountryCode);
    }

    this.pickupForm.get('cPickupEmail')?.setValue(filterValue.cEmailAddress);
    this.pickupForm.get('cPhone')?.setValue(filterValue.cContactNumber);
    this.pickupForm?.get('cPickupReferenceNumber')?.reset();
    this.pickupForm?.get('tPickupDate')?.reset();
    this.pickupForm?.get('tPickupTime')?.reset();
    this.pickupForm?.get('tPickupTimeTo')?.reset();
    this.pickupForm.updateValueAndValidity();
    this.pickupForm.markAllAsTouched();
    this.zipCodeValidate(filterValue);
    this.cdr.detectChanges();
    // this.openDeleteConfirmationDialog(filterValue);
  }

 openDeleteConfirmationDialog(PickupAddress: any): void {
    const dialogRef = this._matDialog.open(DeletePickupDialogComponent, {
      width: '860px',
      data: {
        title: this.translationService.instantTranslate('DELETE-PICKUP-ADDRESS'),
        message: this.translationService.instantTranslate('DELETE-PICKUP-CONFIRMATION'),
        companyName: PickupAddress.cCompanyName,
        contactPerson: PickupAddress.cContactName,
        address: PickupAddress.cAddressLine1,
        state: PickupAddress.cStateName,
        city: PickupAddress.cCityName,
        postalCode: PickupAddress.cPostalCode,
        email: PickupAddress.cEmailAddress,
        phone: PickupAddress.cContactNumber
      },
    });

    dialogRef.afterClosed().subscribe(result => {
      if (result) {
        this.deletePickupDetail(PickupAddress);
      }
    });
  }


  deletePickupDetail(PickupAddress: any): void {
    this.listPickupAddress = this.listPickupAddress.filter((item: { cCompanyName: any; }) => item.cCompanyName !== PickupAddress.cCompanyName);

    this.filteredPickupAddress = this.pickupForm?.get('cCompanyName')?.valueChanges.pipe(
      startWith(''),
      map(origin =>
        origin
        ? this._filterPickup(this.listPickupAddress, origin)
        : this.listPickupAddress && this.listPickupAddress.length
        ? this.listPickupAddress.slice()
        : []
      )
    );

    const observer = {
      next: () => {
        this.resetPickupAddress();
        this.setMultiValidators();
        this.pickupForm.markAllAsTouched();
      },
      error: (error: any) => {
        console.error('Error deleting pickup detail:', error.message);
      },
      complete: () => {
        console.log('Deletion process completed.');
      }
    };

    this._searchService.removePickupAddress(PickupAddress).subscribe(observer);

  }


  shouldHideIcon(cCompanyName: string): boolean {
    const companyNameInInput = this.pickupForm.get('cCompanyName')?.value;
    return this.selectedCompanyName === cCompanyName && companyNameInInput && companyNameInInput.trim() !== '';
  }



  clearCompanyName() {

    this.pickupForm.get('cCompanyName')?.setValue('');
    this.selectedCompanyName = null;

    if (this.autoCompnay && this.autoCompnay.options) {
      this.autoCompnay.options.forEach(option => option.deselect());
    }
    this.pickupForm.markAsUntouched();
    this.cdr.detectChanges();
  }  
 

What I am doing wrong here how do I update the icon and show the mat-icon when we add a word and remove it from selected data

Clique no option do select para abrir o MODAL [closed]

tô tentando adicionar uma funcionalidade no meu codigo de modo que assim que eu clicar na opçao do select Falha Processamento, imediatamente apareça um modal com um textarea e dois botões salvar e cancelar mas somente a interface grafica no entanto tô tentando isso a muito tempo mas não conssigo ou melhor o codigo que eu crio pra tentar fazer isso ccria conflito com outros codigos e as coisas param de funcionar,

 function showDetails(type) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `pedidos.php?type=${type}`, true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            const data = JSON.parse(xhr.responseText);
            let detailsContent = '';

            if (type === 'miniaturas') {
    detailsContent = `<div class="recentOrders">
        <div class="cardHeader">
            <h2>Lista de miniaturas para Imprimir</h2>
           
        </div>
        <table>
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Nota</td>
                    <td>Status</td>
                </tr>
            </thead>
            <tbody>`;
    
    data.forEach(row => {
        detailsContent += `<tr>
            <td>${row.nome_miniatura}</td>
            <td style="color: red;">${row.status === "Falha Processamento" ? "Erro na impressão" : ""}</td>
            <td>
                <form method="POST" action="/novo sistema/pedido/status/update_status.php">
                    <input type="hidden" name="id" value="${row.id}">
                    <select name="status" ${row.status === "Concluido" ? "disabled" : ""}>
                        <option value="Nao Concluido" ${row.status === "Nao Concluido" ? "selected" : ""}>Nao Concluido</option>
                        <option value="Concluido" ${row.status === "Concluido" ? "selected" : ""}>Concluido</option>
                        <option value="Montados" ${row.status === "Montados" ? "selected" : ""}>Pintado</option>
                    </select>
                    <button type="submit" ${row.status === "Concluido" ? "disabled" : ""}>Atualizar</button>
                </form>
            </td>
        </tr>`;
    });

    detailsContent += `</tbody></table></div> <div class="footer">
    <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
</div>`;
}




else if (type === 'guarda') {
    detailsContent = `<div class="recentOrders">
        <div class="cardHeader">
            <h2>Lista de miniaturas para Passar Tinta de Guarda</h2>
        </div>
        <table>
            <thead>
                <tr>
                    <td>Name</td>
                    <td>Status</td>
                </tr>
            </thead>
            <tbody>`;
    
    data.forEach(row => {
        detailsContent += `<tr>
            <td>${row.nome_miniatura}</td>
            <td>
                <form method="POST" action="/novo sistema/pedido/status/update_status.php">
                    <input type="hidden" name="id" value="${row.id}">
                    <select name="status">
                        <option value="Guarda" ${row.status === 'Guarda' ? 'selected' : ''}>Guarda</option>
                        <option value="Falha" ${row.status === 'Falha' ? 'selected' : ''}>Falha</option>
                    </select>
                    <button type="submit">Atualizar</button>
                </form>
            </td>
        </tr>`;
    });

    detailsContent += `</tbody></table></div> <div class="footer">
    <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
</div>`;
}




 


else if (type === 'montar') {
                detailsContent = `<div class="recentOrders">
                    <div class="cardHeader">
                        <h2>Lista de miniaturas para Montar</h2>
                       
                    </div>
                    <table>
                        <thead>     
                            <tr>
                                <td>Name</td>
                                <td>Status</td>
                            </tr>
                        </thead>
                        <tbody>`;
                
                data.forEach(row => {
                    detailsContent += `<tr>
                        <td>${row.nome_miniatura}</td>
                        <td>
                            <form method="POST" action="/novo sistema/pedido/status/update_status.php">
                                <input type="hidden" name="id" value="${row.id}">
                                <select name="status" ${row.status === "Montado" || row.status === "Falha" || row.status === "Falha Processamento" ? "disabled" : ""}>
                                    <option value="Montado" ${row.status === "Montado" ? "selected" : ""}>Montado</option>
                                    <option value="Falha" ${row.status === "Falha" ? "selected" : ""}>Falha</option>
                                    <option value="Falha Processamento" ${row.status === "Falha Processamento" ? "selected" : ""}>Falha Processamento</option>
                                </select>
                                <button type="submit" ${row.status === "Montado" || row.status === "Falha" || row.status === "Falha Processamento"? "disabled" : ""}>Atualizar</button>
                            </form>
                        </td>
                    </tr>`;


                    
                });

                detailsContent += `</tbody></table></div> <div class="footer">
        <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
    </div>`;
            } 

             else if (type === 'caixas') {
    detailsContent = `<div class="recentOrders">
        <div class="cardHeader">
            <h2>Lista de caixas para Preparar</h2>
            
        </div>
        <table>
            <thead>
                <tr>
                    <td>Caixa</td>
                    <td>Miniatura</td>
                    <td>Status</td>
                </tr>
            </thead>
            <tbody>`;
    
    let caixa_numero = 1;

    // Itera sobre os dados recebidos
    data.forEach(row => {
        // Divide as miniaturas em uma lista, considerando a separação por 'n'
        const miniaturas = row.miniaturas.split('n');
        miniaturas.forEach(miniatura => {
            // Adiciona uma linha na tabela para cada miniatura
            detailsContent += `<tr>
                <td>Caixa ${caixa_numero} - ${row.nome_order}</td>
                <td>${miniatura}</td>
                <td>
                    <form method="POST" action="/novo sistema/pedido/status/update_status.php">
                        <input type="hidden" name="id" value="${row.id}">
                        <select name="status">
                            <option value="Pronto" ${row.status === "Pronto" ? "selected" : ""}>Pronto</option>
                            <option value="Falha" ${row.status === "Falha" ? "selected" : ""}>Falha</option>
                        </select>
                        <button type="submit">Atualizar</button>
                    </form>
                </td>
            </tr>`;
        });

        // Incrementa o número da caixa após adicionar todas as miniaturas
        caixa_numero++;
    });

    detailsContent += `</tbody></table></div> <div class="footer">
        <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
    </div>`;

    // Atualiza o conteúdo da página com o HTML gerado
    document.getElementById('details').innerHTML = detailsContent;
}

else if (type === 'Rasteiartudo') {
    detailsContent = `<div class="recentOrders">
        <div class="cardHeader">
            <h2>Lista de Caixas Rasteadas</h2>
           
        </div>
        <table>
            <thead>
                <tr>
                    <td>Caixas</td>
                    <td>Código de Rastreamento</td>
                    <td>Data</td>
                </tr>
            </thead>
            <tbody>`;
    
    let caixa_numero = 1;
    data.forEach(row => {
        detailsContent += `<tr>
            <td>Caixa ${caixa_numero} - ${row.nome_order}</td>
            <td>${row.codigo_rastreio}</td>
            <td>${row.data}</td>
        </tr>`;
        caixa_numero++;
    });

    detailsContent += `</tbody></table></div> 
    <div class="footer">
        <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
    </div>`;

    // Atualiza o conteúdo da página com o HTML gerado
    document.getElementById('details').innerHTML = detailsContent;
}











else if (type === 'progresso') {
    let selectedStatus = {};

     // Retrieve stored selected status on page load
  selectedStatus = JSON.parse(localStorage.getItem('selectedStatus')) || {};

    
    detailsContent = `<div class="recentOrders">
        <div class="cardHeader">
            <h2>Progresso das Caixas</h2>
        </div>
        <table>
            <thead>
                <tr>
                    <td>Caixas</td>
                    <td class="status-column">STP</td>
                    <td class="status-column">CTT Portugal</td>
                    <td class="status-column" style="text-align:left;">Finalizado</td>
                </tr>
            </thead>
            <tbody>`;

    let caixa_numero = 1;
    data.forEach(row => {
        let codigoRastreamento = row.codigo_rastreio ? 1 : 0;  // Se código de rastreio não for nulo, considera fase 1 como ativada
        
        // Define o status atual para a caixa
        let stpChecked = codigoRastreamento === 1 ? 'checked' : '';
        let cttChecked = codigoRastreamento === 2 ? 'checked' : '';
        let finalizadoChecked = codigoRastreamento === 3 ? 'checked' : '';
        
        detailsContent += `<tr>
            <td>Caixa ${caixa_numero} -» ${row.nome_order}</td>
            <td class="status-column"><input type="radio" name="status_${caixa_numero}" value="stp" ${stpChecked}></td>
            <td class="status-column"><input type="radio" name="status_${caixa_numero}" value="ctt" ${cttChecked}></td>
            <td class="status-column"><input type="radio" name="status_${caixa_numero}" value="finalizado" ${finalizadoChecked}  style="display: flex;
    justify-content: center;
    align-items: center;"></td>
        </tr>`;
        caixa_numero++;
    });

    detailsContent += `</tbody></table></div> 
    <div class="footer">
        <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
    </div>`;

    // Atualiza o conteúdo da página com o HTML gerado
    document.getElementById('details').innerHTML = detailsContent;
}

















 



 




        
    };
    xhr.send();


<!-- Modal HTML -->
<div id="falhaModal" style="display: none;">
    <div style="background-color: #f1f1f1; padding: 20px; border-radius: 10px; width: 300px; margin: auto; position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 1000;">
        <h3>Informe o motivo da falha</h3>
        <textarea id="falhaMotivo" rows="4" style="width: 100%;"></textarea>
        <br><br>
        <button id="salvarFalha">Salvar</button>
        <button id="cancelarFalha">Cancelar</button>
    </div>
    <div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0,0,0,0.5); z-index: 999;" id="modalOverlay"></div>
</div>

<!-- Seu select existente -->
<select id="statusSelect">
    <option value="sucesso">Sucesso</option>
    <option value="falha">Falha Processamento</option>
    <!-- Outras opções -->
</select>

<!-- Script JS para mostrar o modal -->
<script>
    document.getElementById('statusSelect').addEventListener('change', function() {
        var selectedOption = this.value;
        if (selectedOption === 'falha') {
            document.getElementById('falhaModal').style.display = 'block';
        }
    });

    document.getElementById('salvarFalha').addEventListener('click', function() {
        var motivo = document.getElementById('falhaMotivo').value;
        if (motivo.trim() === '') {
            alert('Por favor, informe o motivo da falha.');
        } else {
            console.log('Motivo da falha salvo:', motivo);
            document.getElementById('falhaModal').style.display = 'none';
        }
    });

    document.getElementById('cancelarFalha').addEventListener('click', function() {
        document.getElementById('falhaModal').style.display = 'none';
    });

    document.getElementById('modalOverlay').addEventListener('click', function() {
        document.getElementById('falhaModal').style.display = 'none';
    });
</script>


```   testei isso separadamente funcionou perfeitamente, mas o problema é que quando eu tento adaptar a este trecho do codigo aqui, não funciona e ainda interfere no funcionamento de outros

else if (type === ‘montar’) {
detailsContent = `

Lista de miniaturas para Montar

                </div>
                <table>
                    <thead>     
                        <tr>
                            <td>Name</td>
                            <td>Status</td>
                        </tr>
                    </thead>
                    <tbody>`;
            
            data.forEach(row => {
                detailsContent += `<tr>
                    <td>${row.nome_miniatura}</td>
                    <td>
                        <form method="POST" action="/novo sistema/pedido/status/update_status.php">
                            <input type="hidden" name="id" value="${row.id}">
                            <select name="status" ${row.status === "Montado" || row.status === "Falha" || row.status === "Falha Processamento" ? "disabled" : ""}>
                                <option value="Montado" ${row.status === "Montado" ? "selected" : ""}>Montado</option>
                                <option value="Falha" ${row.status === "Falha" ? "selected" : ""}>Falha</option>
                                <option value="Falha Processamento" ${row.status === "Falha Processamento" ? "selected" : ""}>Falha Processamento</option>
                            </select>
                            <button type="submit" ${row.status === "Montado" || row.status === "Falha" || row.status === "Falha Processamento"? "disabled" : ""}>Atualizar</button>
                        </form>
                    </td>
                </tr>`;


                
            });

            detailsContent += `</tbody></table></div> <div class="footer">
    <p>&copy; 2024 Sistema Interno - Todos os direitos reservados.</p>
</div>`;
        } 

CrudField JavaScript Library with relationship/subfield fields

I have a crud with a relationship type and subfields:

'name'  => 'serviceProvider',
'type'  => 'relationship',
'label' => 'Services Provider',
'subfields'   => [
    [
        'name'  => 'cost',
        'label' => 'Cost',
        'type'  => 'number',
        'attributes' => ["step" => "any"], // allow decimals
        'wrapper' => [
            'class' => 'form-group col-sm-4'
        ],
    ],
    [
        'name'  => 'is_no_tarif_cost',
        'label' => 'Cost without tarif',
        'type'  => 'checkbox',
        'wrapper' => [
            'class' => 'form-group col-sm-2 d-flex align-items-end'
        ],
    ],
]

and I want to make it so that when the field is_no_tarif_cost is changed, a console log of the changed rowNumber

crud.field('serviceProvider').subfield('is_no_tarif_cost').onChange(function(field) {
    console.log('hey i am here on row: ' + field.rowNumber) 
});

I did everything according to the documentation, but it doesn’t work. No JavaScript errors in the console. It’s as if the hook is being hung on the wrong object. Any ideas what the error might be?

How do I know if an error was handled in a .catch() block when using rtk-query middleware?

I use rtk-query and I have a mutation query. After the query is executed, some actions are performed in the .then() block and then the error is processed in .catch().
Also, a middleware is written that catches all errors of all queries in the project and displays them as notifications for the user.

The task is to determine inside the middleware whether the .catch() block was called or not and, based on this condition, perform some actions in the middleware.

I looked inside the action objects that the middleware gives me, but there is no hint of a .catch() block.

Is this even possible?

Issue Passing Data to Angular Component – Some Input Properties are Undefined in One Instance data passed using Input-Output

I have an Angular component where I am passing multiple input properties and binding methods for event handling as shown below:

<component
  [x]="x"
  [y]="y"
  [z]="z"
  [a]="a"
  [b]="b"
  [c]="c"
  (method1)="method1($event)"
  (method2)="method2($event)"
></component>

In one instance of the component, the data is passed correctly, and everything works as expected. However, in another instance, some of the input properties ([x], [y], [z], etc.) are being passed as undefined.

What I Want to Understand:

Why might the data be passed as undefined in one instance but correctly in another?
What could cause some input properties to not bind correctly or appear as undefined?
Are there specific debugging steps I should take to ensure the data is passed consistently across instances?

Additional Context:

I'm using Angular version 16.0.0.
The parent component is responsible for passing the data.
No errors are logged in the console, but some input properties are unexpectedly undefined.

Any insights on why this might be happening and how to solve this issue would be greatly appreciated!

Things I Have Checked:

Component Initialization: The inputs are initialized and passed from the parent component.
Data Binding: The data being passed from the parent is valid and exists at the time of initialization.
Lifecycle Hooks: I have verified that the data is available in the parent component during the ngOnInit and ngAfterViewInit phases.In 1st instance data is getting passed in another instance data is not getting passed (Passed as undefined).

Failed to fetch error with PUT request, MyBatis Mapper method not executing properly

Question:

I’m encountering an issue where a PUT request is failing with a Failed to fetch error, and the corresponding MyBatis Mapper method is not executing properly. Here’s a breakdown of the problem and what I’ve tried so far:

Problem Description

When I attempt to update a user profile using a PUT request, the server receives the request, but it remains in a pending state indefinitely. The server logs show that the method handling the request is called, but the MyBatis Mapper method does not seem to execute as expected. The database is not updated, and no error messages are being logged.

Code Snippets

JavaScript Code:

document.addEventListener('DOMContentLoaded', function () {
  const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
  const csrfHeader = 'X-CSRF-TOKEN';

  const pfpContainer = document.getElementsByClassName("pfp-container")[0];
  const soloProfilePicture = document.getElementById("solo-pfp");
  const pfpInput = document.getElementById("solo-pfp-file-input");
  const saveBtn = document.getElementById("save-profile-update-btn");

  pfpContainer.addEventListener("click", function () {
    pfpInput.click();
  });

  pfpInput.addEventListener("change", function (changeEvent) {
    const file = changeEvent.target.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function (loadEvent) {
        soloProfilePicture.src = loadEvent.target.result;
      };
      reader.readAsDataURL(file);
    }
  });

  saveBtn.onclick = function (event) {
    console.log("click");
    const data = {
      profileImageUrl: document.getElementById("solo-pfp").src,
      email: document.getElementById("email").innerText
    };

    fetch('/api/user/solo/update-profile', {
      method: 'PUT',
      headers: {
        [csrfHeader]: csrfToken,
        'Content-Type': 'application/json; charset=utf-8'
      },
      body: JSON.stringify(data)
    })
    .then(response => response.json())
    .then(resp => {
      alert("User Info Edit complete");
      window.location.href = "/";
    })
    .catch(error => {
      alert(JSON.stringify(error));
    });
  });
});

Spring Boot Controller Code:

@PutMapping({"/solo/update-profile"})
public ResponseEntity<?> updateProfileProcess(@RequestBody UserResponseDTO user,
    HttpSession session) {
  log.info("UserResponseDTO 생성 성공");
  log.info("1. updateProfileProcess 호출됨");
  log.info("2. Received user data: {}", user);
  try {
    userService.updateProfileImageUrl(user);
    log.info("3. updateProfileImageUrl 호출됨");
  } catch (Exception e) {
    log.error("Error updating profile image URL: ", e);
    return ResponseEntity.badRequest().body("Error updating profile: " + e.getMessage());
  }

  Authentication auth = SecurityContextHolder.getContext().getAuthentication();
  log.info("4. Authentication 객체 생성됨");
  if (auth != null && auth.isAuthenticated()) {
    log.info("5. 세션이 NULL이 아니고 로그인이 되어있음");
    session.setAttribute("profileImageUrl", user.getProfileImageUrl());
    log.info("6. 세션에 정보 삽입함");
  }
  return ResponseEntity.ok()
      .body(Map.of("message", "Profile updated successfully", "redirectUrl", "/user/solo/"));
}

MyBatis Mapper XML Code:

<mapper namespace="com.spring.moji.mapper.UserMapper">
  <resultMap id="userMap" type="com.spring.moji.entity.UserEntity">
    <id column="email" property="email"/>
    <result column="user_name" property="userName"/>
    <result column="birthday" property="birthday"/>
    <result column="gender" property="gender"/>
    <result column="password" property="password"/>
    <result column="created_at" property="createdAt"/>
    <result column="profile_image_url" property="profileImageUrl"/>
    <result column="couple_id" property="coupleId"/>
    <collection property="authList" resultMap="authMap"/>
  </resultMap>
  <resultMap id="authMap" type="com.spring.moji.entity.UserAuthEntity">
    <id column="auth_no" property="authNo"/>
    <result column="user_email" property="userEmail"/>
    <result column="auth" property="auth"/>
  </resultMap>

  <select id="login" resultMap="userMap">
    SELECT u.email, u.user_name, birthday, gender, password, profile_image_url, auth, couple_id
    FROM users u
    JOIN user_auth auth ON u.email = auth.user_email
    WHERE u.email = #{email}
  </select>

  <insert id="join">
    INSERT INTO users (email, user_name, birthday, gender, password, created_at)
    VALUES (#{email}, #{userName}, #{birthday}, #{gender}, #{password}, sysdate)
  </insert>

  <insert id="insertAuth">
    INSERT INTO user_auth (auth_no, user_email, auth)
    VALUES (user_auth_seq.nextval, #{userEmail}, #{auth})
  </insert>

  <update id="updateProfileImageUrl" parameterType="com.spring.moji.entity.UserEntity">
    UPDATE users
    SET profile_image_url = #{profileImageUrl}
    WHERE email = #{email}
  </update>
</mapper>

Troubleshooting Steps Taken

  1. Server Logs: Checked the server logs but did not find any specific errors or warnings related to the request processing.

  2. JavaScript Fetch API: Verified that the fetch request is properly configured with the correct CSRF token and headers.

  3. Network Activity: Monitored network activity and confirmed that the request is sent but remains in a pending state.

  4. Database Check: Ensured that the database connection and the updateProfileImageUrl query are properly configured.

Questions

  1. Why might the PUT request remain in a pending state and not complete?
  2. What could be causing the MyBatis Mapper method not to execute or update the database?
  3. Are there any common issues or misconfigurations in the provided code snippets that could lead to this problem?

I would appreciate any guidance or suggestions to resolve this issue. Thank you!

Why can I change the HTML text on state change but I can’t change the HTML class? [closed]

I have a React component that looks something like this:

enter image description here

It is a simple table built by iterating over a state variable called clientOrders. For each “order” in clientOrders I render a row. Each row has a button that when pressed changes the Boolean value of order.status.

At the moment, when I click on the button, the status changes correctly from “Pending” (order.status is false) to “Done” (order.status is true).

What doesn’t work is the HTML classes that are being applied to the element. The background color is always red and I want it to be green when order.status is true.

For example, in the attached image, you can see that the first row has a status of Done, so I’d like to render that with a green background.

const RestaurantActions = () => {
    const [clientOrders, setClientOrders] = useState([])


    // When the "Change status" button is pressed, change the state corresponding to that row
    const handleButton = (rowId: number) => {
        setClientOrders(clientOrders.map(row => 
            row.id === rowId ? { ...row, status: !row.status } : row
        ));
    }

    return (
        ...
        {/* Render a column for each "order" stored in the state */}
        { clientOrders.map(order => (
            <tr>
            <td>
                {/* If the status of the order is true, render it with a green background. This doesn't work. */}
                {/* If the status of the order is false, render it with a red background. This doesn't work. */}
                <span className="{ order.status ? bg-green-50 : bg-red-100 }">
                    {/* If the status of the order is true, display the text "Done". This works. */}
                    {/* If the status of the order is false, display the text "Pending". This works. */}
                    { order.status ? 'Done' : 'Pending' }
                </span>
            </td>
            <td>
                <button onClick={() => handleAButton(order.id)}>
                Mark as done / pending
                </button>
            </td>
            </tr>
        ))}
        ...

    )

}

Why can I change the text of the Staus column (“Pending” <—> “Done”), but not the background and text color (Green <—> Red)?