I’m starting to get my hands into web development, Should I learn React or Do projects on vanilla JavaScript in the beginning

I’m an aspiring full-stack developer currently enhancing my skills. I have a basic understanding of HTML and CSS, and I’m now looking to dive deeper into JavaScript and its frameworks. However, I’m at a crossroads and need some advice.

Should I start by mastering Vanilla JavaScript before moving on to React, or can I jump straight into learning React?

Here are a few points about my current situation:

I have some experience with basic programming concepts.
My ultimate goal is to build dynamic and responsive web applications.
I enjoy learning through practical projects and hands-on experience.
I’ve read that understanding the fundamentals of JavaScript is crucial, but I’ve also seen recommendations to start with React to quickly build real-world applications. What would be the best approach for someone in my position?

Any insights or personal experiences would be greatly appreciated!

Thanks in advance!

Unable to import any module for nextjs

I’m having some trouble with my Next.js project and I’m hoping someone here might be able to help. Here’s the situation:

Issue: I’m trying to import modules in my Next.js project, but I keep running into errors indicating that modules cannot be resolved. For instance, when trying to import react-chartjs-2, I get the error Module not found: Can’t resolve ‘react-chartjs-2’.

Setup:

Next.js Version: 14.2.12 (as indicated in package.json)

Error Message: Next.js (14.2.5) out of date when running the project, even though package.json lists version 14.2.12.

Folder Structure: I have two directories in my project: nextjs and fastapi. Inside nextjs, there’s a node_modules folder and a package.json file.

Questions:

Why is there a version mismatch between package.json and the build error message?

Are there any issues or steps I might have missed that could cause modules to not be resolved correctly?

How can I make sure that my Next.js environment is correctly set up and using the right version?

Steps Taken:

I ran npm install in the nextjs folder to install dependencies and have tried reinstalling the dependency as well.

I’ve tried deleting and reinstalling node_modules but still get the same errors.

I checked that the correct Next.js version is listed in package.json, but the build process seems to be using an outdated version.

I’ve also tried npm i next@latest as well

Laravel javascript variable get in blade file

I need get js var in view blade file.
I got this one in Controller and got success in console
in route file

Route::post('/some-route', [Controller::class, 'someMethod']);
Route::post('/some-route', 'Controller@someMethod');//this also work

in js file in $(“#applyBonus”).on(“click”, function () method

$.ajax({ 
    url: base_url + '/some-route', // The route to your Laravel controller 
    type: 'POST', 
    data: { 
        someVarName: someInput, // someInput is from blade file input value. got successfully 
         
    }, 
    success: function(response) { 
        console.log(response); //success
        alert("ssuccessss___" + someInput); //success
        
    }, 
    error: function(xhr) { 
        console.error(xhr.responseText); 
        alert("error___");
    } 
}); 

in Controller

public function yourMethod(Request $request) { 
    //$variable = 'someVarName'; //this also work
    $variable = $request->input('someVarName'); 
    
    //return view('frontend.checkout', compact('variable')); // this also work
    //return view('frontend.checkout')->with('variable'); //this also work
    return view('frontend.checkout')->with('variableName', $variable);//success in console and alert message
} 

and now I tried to get this $variable in view.blade.php

@foreach($variable as $varr) //undefined $variable
       <div class="row">{{ $variable }}</div>
       <div class="row">{{ $varr }}</div>
@endforeach

or

echo $variable;
//or next. also span tag
<div class="row">{{ $variable }}</div>

and all time I get error – $variable is undefined

with I want do is to get input value as php $variable.
maybe there other to get $variable from input value without page refresh?
or
How get this variable from controller in view blade file?
Thanks

try get input value via input value->js var -> controller -> blade file. on last step get error $variable undefined

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?