How do I Authenticate Into a Website that uses a csrf token using Axios

The website that I want to authenticate into this website https://homeaccess.katyisd.org/HomeAccess/Account/LogOn?ReturnUrl=%2fHomeAccess and it uses a “__RequestVerificationToken” that always changes when you enter the website and the token is hidden in the html. I checked the payload when I logged in and it sent: Payload When I logged into the website

const axios = require('axios');
const cheerio = require('cheerio');

axios.get('https://homeaccess.katyisd.org/HomeAccess/Account/LogOn')
  .then((response) => {
    const $ = cheerio.load(response.data);
    const token = $('input[name="__RequestVerificationToken"]').val();

    const payload = {
      __RequestVerificationToken: token,
      SCKTY00328510CustomEnabled: 'True',
      SCKTY00436568CustomEnabled: 'True',
      Database: '10',
      VerificationOption: 'UsernamePassword',
      'LogOnDetails.UserName': 'TestName',
      tempUN: '',
      tempPW: '',
      'LogOnDetails.Password': 'TestPass'
    };

    return axios.post('https://homeaccess.katyisd.org/HomeAccess/Account/LogOn', payload);
  })
  .then((response) => {
    console.log(response.data);
  })
  .catch((error) => {
    console.error(error);
  });

When I tried this, all I got were errors and I am not sure why.

Google Script – findText is not defined

I’m trying to make a script for my Google document so I can format specific paragraphs in some “chat log” segments according to the nickname the paragraph begins with (example: “myNickname: blah blah blah”).

I made a test function to test out findText() but when I execute test(), it returns this error: ReferenceError: findText is not defined test @ Code.gs:21

Here is the complete script:

function onOpen(e) {
  DocumentApp.getUi()
  .createMenu("FORMATTING")
    .addItem("Test", "test")

  .addToUi();
}

function formatNickname(nickname, style) {
  nickname = nickname + ":"; // Dialogue is in a 'chat log' format, so it's displayed as "NICKNAME: Blah blah blah"

  let foundText = findText(nickname); 

  foundText.getText().setTextStyle(style);

  console.log(foundText); // Debug
}

function test() {
  formatNickname("BAB", findText("AA:").getText.getTextStyle()); // The second parameter is for debug reasons. AA is a character with a specific text style.
}

And here is my appsscript.json:

{
  "oauthScopes": [
    "https://www.googleapis.com/auth/documents.currentonly",
    "https://www.googleapis.com/auth/documents"
  ],
  "timeZone": "America/Sao_Paulo",
  "dependencies": {
  },
  "exceptionLogging": "STACKDRIVER",
  "runtimeVersion": "V8"
}

I have Google Apps Script API turned on in my user settings, as instructed in this answer.

Chrome Extension APIs

I’m building an extension for myself, so I can add Ethereum or BNB wallets and see their balances. But when I put the wallet and press “Add”, I get errors that I don’t know how to solve anymore.

Extension

At first I was getting an API error, then I don’t get any more, but now I get these two errors:

Console Error

I leave the complete JSON:

const walletForm = document.getElementById("walletForm");
    const walletAddress = document.getElementById("walletAddress");
    const totalBalance = document.getElementById("totalBalance");
    const walletList = document.getElementById("walletList");
    
    walletForm.addEventListener("submit", (e) => {
      e.preventDefault();
      const address = walletAddress.value.trim();
    
      if (address) {
        addWallet(address);
      }
    
      walletAddress.value = "";
    });
    
    const ETHERSCAN_API_KEY = "FAKEAPI";
    const BSCSCAN_API_KEY = "FAKEAPI";
    
    async function addWallet(address) {
      try {
        const ethereumBalance = await getEthereumBalance(address);
        const bnbBalance = await getBNBBalance(address);
        // Resto del código para agregar la billetera
      } catch (error) {
        console.error(`Error en la función addWallet: ${error.message}`);
      }
    }
    
    async function getEthereumBalance(address) {
      try {
        const response = await fetch(`https://api.etherscan.io/api?module=account&action=balance&address=${address}&tag=latest&apikey=FAKEAPI`);
        if (!response.ok) {
          throw new Error(`Error en la respuesta de la API: ${response.statusText}`);
        }
        const data = await response.json();
        if (data.message === 'OK') {
          console.log(`Resultado de la llamada de API: ${data.result}`);
          return BigInt(data.result);
        } else {
          throw new Error(`Error en la respuesta de la API: ${data.message}`);
        }
      } catch (error) {
        console.error(`Error en la función getEthereumBalance: ${error.message}`);
        return null;
      }
    }
    
    async function getBNBBalance(address) {
      try {
        const response = await fetch(`https://api.bscscan.com/api?module=account&action=balance&address=${address}&tag=latest&apikey=D96DAB88GRZY5UZ3YFJSZMUVA6E5H8EMU8`);
        if (!response.ok) {
          throw new Error(`Error en la respuesta de la API: ${response.statusText}`);
        }
        const data = await response.json();
        if (data.message === 'OK') {
          console.log(`Resultado de la llamada de API: ${data.result}`);
          return BigInt(data.result);
        } else {
          throw new Error(`Error en la respuesta de la API: ${data.message}`);
        }
      } catch (error) {
        console.error(`Error en la función getBNBBalance: ${error.message}`);
        return null;
      }
    }

Its just an extension, why is so hard? I feel the problem in the API code, but.. I dont knok.

TypeError: cannot assign to read only property ‘referenceControl’ of object ‘[object Object]’ Typescript + Angular

The below class has the following properties, which is auto-generated form swagger library

export class GetControlForPolicyDesignerView implements IGetControlForPolicyDesignerView {
    control!: ControlDto;
    referenceControl!: AuthorityProvisionListDto[] | undefined;
    referenceCount!: number;
    association!: boolean;
    selected!: boolean;
    statements!: StatementViewDto[] | undefined;
    // ......
}

Interface

export interface IGetControlForPolicyDesignerView {
    control: ControlDto;
    referenceControl: AuthorityProvisionListDto[] | undefined;
    referenceCount: number;
    association: boolean;
    selected: boolean;
    statements: StatementViewDto[] | undefined;
}

In one of the class in Angular, I am assigning the value to the property below

Initialize the property at the beginning

selectedControl: GetControlForPolicyDesignerView = new GetControlForPolicyDesignerView();

Then assign the value to the property

this._guidanceBuilderDataService.selectedControlUpdate.pipe(takeUntil(this.unsubscribe)).subscribe((selectedControl) => {
                this.selectedControl.referenceControl= selectedControl?.referenceControl;
                this.selectedControl.referenceCount = selectedControl?.referenceCount;
                this.selectedControl.statements = selectedControl?.statements;
        });

Error

ERROR TypeError: Cannot assign to read only property 'referenceControl' of object '[object Object]'
    at SafeSubscriber._next (guidance-designer.component.ts:223:99)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)
    at Subscriber.next (Subscriber.js:49:1)
    at TakeUntilSubscriber._next (Subscriber.js:72:1)
    at TakeUntilSubscriber.next (Subscriber.js:49:1)
    at SafeSubscriber.__tryOrUnsub (Subscriber.js:183:1)
    at SafeSubscriber.next (Subscriber.js:122:1)
    at Subscriber._next (Subscriber.js:72:1)

Tried code, but didn’t worked

(this.selectedControl.referenceControl as AuthorityProvisionListDto[]) = selectedControl?.referenceControl;

How to create a mask layer from a user uploaded image in P5js

I’m trying to create a generative canvas which has multiple grid layout options (a mix of square, rectangle and circles) and allows a user to upload an image to the canvas. The image should be masked by for example the circle shape that sits ontop of the main grid structure and fit the shape by width or height in grid option 1 for example.

What is a good way to go about this so that the uploaded image can be reused in say in grid option three but masked in a rectangle? Each grid layout offers different spaces in which the image can be masked by a shape.

The selection of a grid option is controlled by a range slider.

I have tried it my side and the image uploads but sits behind the grid layout at a large size.

my code also uses HTML & CSS.

Thanks

Why is it faster to fetch a resource, create an object URL, and set an iframe’s src attribute to that, than to set src to that resource directly?

Recently I was creating a print button for a report. I wanted the print button to use the PDF version of the report for cross-browser consistency. At first I fetch()ed the PDF, got the blob, created an object URL, and set the iframes src property to that URL.

Later I realized I could just set the iframe`s src to the PDF URL in the first place. But that turned out to be slower by ~400ms on a 5s request. In fact the speed difference seems to scale with the length of the request.

Even when just loading a JSON file, as in the snippet below, the speed difference persists.

Here’s a codepen where you can fiddle with the tests yourself. I tried re-arranging and adding cache-busting query-string parameter to eliminate. But fetch() is still faster ~90% of the time.

const iframe = document.getElementById("iframe");
const testUri = "https://hacker-news.firebaseio.com/v0/topstories.json";
const fastestEl = document.getElementById('fastest')

async function runTests() {
  const srcTime = await measureLoadTimeUsingSrc()
  const fetchTime = await measureLoadTimeUsingFetch()

  document.getElementById("srcTime").textContent = srcTime;
  document.getElementById("fetchTime").textContent = fetchTime;
  
  if (srcTime < fetchTime) {
    fastestEl.textContent = 'src'
  } else if (fetchTime < srcTime) {
    fastestEl.textContent = 'fetch'
  } else {
    fastestEl.textContent = 'tie'
  }
}

function measureLoadTimeUsingSrc() {
  return new Promise((resolve, reject) => {
    const startTime = performance.now()
    iframe.src = testUri;
    iframe.addEventListener(
      "load", 
      () => resolve(performance.now() - startTime), 
      { once: true }
    );
  });
}

function measureLoadTimeUsingFetch() {
  return new Promise((resolve, reject) => {
    const startTime = performance.now()
    fetch(testUri)
      .then((result) => result.blob())
      .then((blob) => {
        iframe.src = URL.createObjectURL(blob);
        iframe.addEventListener(
          "load", 
          () => resolve(performance.now() - startTime), 
          { once: true }
        );
      })
      .finally(() => URL.revokeObjectURL(iframe.src));
  });
}
<dl>
  <dt>Time using <code>iframe.src = '…'</code><dt>
  <dd id="srcTime">…</dd>
  <dt>Time using <code>fetch('…')</code><dt>
  <dd id="fetchTime">…</dd>
  <dt>Fastest</dt>
  <dd id="fastest">…</dd>
</dl>

<iframe id="iframe" hidden></iframe>
  
<button type="button" onclick="runTests()">
  Run tests
</button>

Exclude Series from Default/Auto Visible Range – Lightweight Charts

We’re using line series to plot moving averages, and occasionally the moving averages are far enough away from the price series (candlesticks) that the price series becomes very small and compressed when lightweight charts auto-sizes the visible frame. A solution to this would be to allow the chart to exclude certain series when setting the visible range. Is this possible? If there is not an API (and far as I can tell there is not), then is there a hack/workaround? This would be particularly useful when using line series for trendlines.

How to access RapidAPI text to speech api

https://rapidapi.com/appsplosionhelp/api/ai-text-to-code-generation/

This api doesn’t use a /get, but it uses a post, so what would I put in the params to access the api.

export const articleApi = createApi({
reducerPath:’articleApi’,
baseQuery:fetchBaseQuery({
baseUrl: ‘https://ai-text-to-code-generation.p.rapidapi.com/’,
prepareHeaders: (headers) => {
headers.set(‘X-RapidAPI-Key’, ‘rapidApiKey’);
headers.set(‘X-RapidAPI-Host’, ‘ai-text-to-code-generation.p.rapidapi.com’);

        return headers;
    }
}),
endpoints:(builder) => ({
    getSummary: builder.query({
        query: (params) => 'Generate Code from Natural Language?url=${encodeURIComponent(params.articleUrl)}&length=3'
    })
})

});

Creating applications for iOS and Android platforms

Creating applications for iOS and Android platforms.

Business Logic Will Be Very Simple

  • Track location (background or foreground) and push updates to our web server
  • Display a List of Jobs (received by our existing API)
  • Utilize 3rd Party Plugin to track locations and if close to a Job Site notify User using Notification that allows them to open up the Job Details

Updating values on frontend but returning NaN

I am trying to automatically update and refresh my item total in my cart page when an item quantity is updated. I keep getting an a return of NaN. I also see a console log of price is undefined, but I don’t know how to solved this.

Script:

  function updateCartItem(cartId, cartItemId, quantityToAdd, csrftoken, price) {
    console.log('price:', price);
    fetch(`/api/carts/${cartId}/items/${cartItemId}/`, {
      method: "PATCH",
      headers: {
        "Content-Type": "application/json",
        "X-CSRFToken": csrftoken,
      },
      body: JSON.stringify({
        quantity: quantityToAdd,
      }),
    })
      .then((response) => response.json())
      .then((data) => {
        console.log("Cart successfully updated:", data);
        console.log("CART:", cartId)
        fetch("/cart/")
        .then((response) => response.text())
        .then((html) => {
            // update the cart items and total price on the page with the new cart data
            const parser = new DOMParser();
            const doc = parser.parseFromString(html, "text/html");
            const itemsContainer = document.getElementById("cart-items");
            const totalContainer = document.getElementById("cart-total");
            if (itemsContainer) {
                itemsContainer.innerHTML = doc.getElementById("cart-items").innerHTML;
            }
            if (totalContainer) {
                totalContainer.textContent = doc.getElementById("cart-total").textContent;
            }
            const itemTotalContainer = document.getElementById(`item-total-${cartItemId}`);
            console.log('itemTotalContainer:', itemTotalContainer);
                    if (itemTotalContainer) {
                        const quantity = parseInt(itemTotalContainer.dataset.quantity);
                        const newQuantity = quantity + quantityToAdd;
                        const newTotal = newQuantity * price;
                        itemTotalContainer.textContent = `£${newTotal.toFixed(2)}`;
                        itemTotalContainer.dataset.quantity = newQuantity;
                    }
        })
        .catch((error) => {
            console.error(error);
        });
    updateItemQuantity(); // update the quantity values on the page after the cart has been updated
    updateCartQuantity(); // update the total cart quantity on the page
    });
}

Html:

<div class="cart--box__item" id="item-total-{{item.id}}" data-quantity="{{ item.quantity }}">£{{item.total}}</div>

How do I write these api calls with query parameters Angular 15? I understand the flow, but I can’t sort out how to implement

A user fills out a form, that form calls an api which prompts an email. The user clicks a link in the email:
localhost:3600/doggydaycare/confirm?confirmid=clkjdkjd439827

I need to write a GET DogDoggyDayCare/DoggyDayCareStatus?doggydaycareId=clkjdkjd439827 (initial status will be 404)

Then my POST DogDoggyDayCare/DoggyDayCareConfirmEmail { “doggydaycareId”: clkjdkjd439827 }

Then hit GET again DogDoggyDayCare/DoggyDayCareStatus?doggydaycareId=clkjdkjd439827 (initial status will be 200)

I know that I need to do query parameters to grab the id clkjdkjd439827, but I can’t for the life of me sort out how to do it? Basically, this email is going to confirm their ID so they can continue in signing up for doggy day care. My head hurts, please help. My ‘postgetstarteddata’ works fine, that’s the one that gets the email. So my email arrives, but I can’t sort out what to do after that.

I got 404 not found for both of them. Please help, I’m desperate.

Service file:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { environment } from 'src/environments/environment';

@Injectable({
    providedIn: 'root'
})
export class GetStartedService {

    constructor(private http:HttpClient) { 
}
    getStatus(){
    return this.http.get(environment.apiUrl + '/DogDoggyDayCare/DoggyDayCareStatus?    doggydaycareId=clkjdkjd439827')
}
    // onboarding basic info post -- onboarding email confirm
    postConfirm(data: any){
    return this.http.post(environment.apiUrl + '/DogDoggyDayCare/DoggyDayCareConfirmEmail', data)
}

    // onboarding basic info post -- onboarding email
    postGetStartedData(data: any){
    return this.http.post(environment.apiUrl + '/DogDoggyDayCare/DoggyDayCareBasicInfo', data)
}
}



confirmation.component.ts file 

import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { GetStartedService } from 'src/app/service/get-started.service';

@Component({
    selector: 'app-confirmation',
    templateUrl: './confirmation.component.html',
    styleUrls: ['./confirmation.component.css']
    })
export class ConfirmationComponent {
    doggydaycareId!: string;
    constructor(private router: ActivatedRoute, 
    private getStatusConfirm:GetStartedService) {}

submitted = true;
ngOnInit() {
this.getStatusConfirm.getStatus().subscribe((data)=>{
    console.log(data);
})
this.router.queryParams
    .subscribe(params=>{
    console.log(params);
    this.doggydaycareId = params['doggydaycareId'];
    console.log(this.doggydaycareId);
    })
this.postConfirmation.postConfirm(this.doggydaycareId).subscribe((doggydaycare)=>{
    console.log(doggydaycare);
})  

}
}

My React page suddenly stopped working with vite, what can I do?

I made a page using React and it was showing just fine two days ago, but today, and without making any changes myself, vite won’t show me my page.
I used to just run npm run dev and vite would expose the page to the localhost, I’d just Ctrl+Click and my page would pop up in Chrome, working flawlessly with React+Router. But now it didn’t and it sent me to the default chrome error screen with the 404 message, telling me that localhost had no web page to display

There is indeed an index.html file in my project, and while it’s under a src folder, again, it used to work just fine earlier.

I’ve tried to look for answers online, but they all seem to relate to Netlify, Github pages or something called nginx that I’m not sure is within my project, I’m trying to run mine locally so the first two examples are out of the picture (at least for now)

I’ve uploaded the whole project to Github and I’d appreciate it if someone could have a look, or just tell me what it’s missing, since it seems like it’s a small easy problem, considering it was running fine earlier.

I’m struggling with minimax algorithm in tic-tac-toe game

I’m currently trying to make a tic-tac-toe game using minimax algorithm. I’m using JavaScript with p5js framework for this project.

Here is the sketch.js code:

var rows = 3;
var cols = 3;
var scl = 1;
var board_width = cols * 100 * scl;
var board_height = rows * 100 * scl;
var board;
let player = 'x';
let ai = 'o';
let playerTurn;
let winner;

var resetBtn;

function setup() {
  
  createCanvas(400, 300);

  resetGame();

  resetBtn = createButton("Reset");
  resetBtn.position(320, 50);
  resetBtn.size(60, 20);
}

function draw() {

  resetBtn.mouseClicked(resetGame);

  winner = checkWinner();

  
  if (winner == 'x' || winner == 'o') {
    console.log(winner);
  }
  else if (winner == 't') {
    console.log("Tie");
  }
  else {
    if (playerTurn == false) {
      aiMove();
      playerTurn = true;
    }
  }

  drawBoard();
  
  
}

function mousePressed() {
  if (playerTurn == true) {
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        if (mouseX > j * 100 && mouseX < (j * 100 + 100) && mouseY > i * 100 && mouseY < (i * 100 + 100)) {
          board[i][j] = player;
          playerTurn = false;
        }
      }
    }
  }
}

function aiMove() {
  let bestScore = -2;
  let score;
  let moveSpot = [];

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (board[i][j] == ' ') {
        board[i][j] = ai;
        score = miniMax(board, false);
        board[i][j] = ' ';
        if (score > bestScore) {
          bestScore = score;
          moveSpot = {i, j};
        }
      }
    }
  }
  board[moveSpot.i][moveSpot.j] = ai;

}

function miniMax(board, isMaximizing) {
  let result = checkWinner();

  if (result == 'x') {
    return -1;
  }
  else if (result == 'o') {
    return 1;
  }
  else if (result == 't') {
    return 0;
  }

  else if (isMaximizing) {
    let bestScore = -2;
    let score;
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        if (board[i][j] == ' ') {
          board[i][j] = ai;
          score = miniMax(board, false);
          board[i][j] = ' ';
          bestScore = max(score, bestScore);
        }
      }
    }
    return bestScore;
  }
  else {
    let bestScore = 2;
    let score;
    for (let i = 0; i < rows; i++) {
      for (let j = 0; j < cols; j++) {
        if (board[i][j] == ' ') {
          board[i][j] = player;
          score = miniMax(board, true);
          board[i][j] = ' ';
          bestScore = min(score, bestScore);
        }
      }
    }
    return bestScore;
  }

}

function checkWinner() {
  
  let w = null;
  
  if (board[0][0] == 'x' && board[0][1] == 'x' && board[0][2] == 'x' ||
            board[1][0] == 'x' && board[1][1] == 'x' && board[1][2] == 'x' ||
            board[2][0] == 'x' && board[2][1] == 'x' && board[2][2] == 'x' ||
            board[0][0] == 'x' && board[1][0] == 'x' && board[2][0] == 'x' ||
            board[0][1] == 'x' && board[1][1] == 'x' && board[2][1] == 'x' ||
            board[0][2] == 'x' && board[1][2] == 'x' && board[2][2] == 'x' ||
            board[0][0] == 'x' && board[1][1] == 'x' && board[2][2] == 'x' ||
            board[2][0] == 'x' && board[1][1] == 'x' && board[0][2] == 'x') {
                return 'x';
        }
        else if (board[0][0] == 'o' && board[0][1] == 'o' && board[0][2] == 'o' ||
            board[1][0] == 'o' && board[1][1] == 'o' && board[1][2] == 'o' ||
            board[2][0] == 'o' && board[2][1] == 'o' && board[2][2] == 'o' ||
            board[0][0] == 'o' && board[1][0] == 'o' && board[2][0] == 'o' ||
            board[0][1] == 'o' && board[1][1] == 'o' && board[2][1] == 'o' ||
            board[0][2] == 'o' && board[1][2] == 'o' && board[2][2] == 'o' ||
            board[0][0] == 'o' && board[1][1] == 'o' && board[2][2] == 'o' ||
            board[2][0] == 'o' && board[1][1] == 'o' && board[0][2] == 'o') {
                return 'o';
        }

        let full = 0;
        for (let i = 0; i < 3; i++) {
            for (let j = 0; j < 3; j++) {
                if (board[i][j] == 'x' || board[i][j] == 'o') {
                    full ++;
                }
            }
        }

        if (full == 9) {
            return 't';
        }

        return winner;
    
  return w;
}

function drawBoard() {
  // draw board
  stroke(0);
  strokeWeight(7);
  line(board_width / 3, 0, board_width / 3, board_height);
  line(board_width / 3 * 2, 0, board_width / 3 * 2, board_height);
  line(0, board_height / 3, board_width, board_height / 3);
  line(0, board_height / 3 * 2, board_width, board_height / 3 * 2);

  for (let i = 0; i < rows; i++) {
    for (let j = 0; j < cols; j++) {
      if (board[i][j] == 'o') {
        circle(j * 100 + 50, i * 100 + 50, 80);
      }
      else if (board[i][j] == 'x') {
        line(j * 100 + 10, i * 100 + 10, j * 100 + 80, i * 100 + 80);
        line(j * 100 + 80, i * 100 + 10, j * 100 + 10, i * 100 + 80);
      }
    }
  }
}

function resetGame() {
  clear();
  winner = null;
  board = [];
  playerTurn = true;
  background(255);

  for (let i = 0; i < rows; i++) {
    let row = [];
    for (let j = 0; j < cols; j++) {
      row[j] = ' ';
    }
    board.push(row);
  }
}

The problem is shown in the picture. As you, the player make first move, if you choose spot 2 then 4 then 6, the ai doesn’t go to spot 9 to win but go to spot 3 instead.
screenshot

I tried this tactic in an example on this website:

https://www.freecodecamp.org/news/how-to-make-your-tic-tac-toe-game-unbeatable-by-using-the-minimax-algorithm-9d690bad4b37/

and got similar result.

Is this a problem with the algorithm implementation or something else?

Thanks,

zod doesn’t revalidate array/object onChange

This sandbox demonstrates the problem.

I have this schema:

  const schema = z.object({
    portals: z.array(
      z
        .object({
          firstName: z.string()
        })
        .refine((data) => data.firstName !== "", {
          message: "First name is required"
        })
    ),
    lastName: z.string().refine((data) => data !== "", {
      message: "Last name is required"
    })
  });
  • firstName is a string inside an object inside an array;
  • firstName only gets revalidated on onSubmit.
  • lastName is just a string;
  • lastName gets revalidated on onSubmit and onChange.

In my real scenario, I have an array which I’d like to revalidate onChange, but I’m unable to.

I’ve heard I could user React Hook Form’s trigger() method but I’m looking for a solution which doesn’t causes re-render at root level.

Does anyone have a solution for this?

Thanks!

@Edit:
For anyone reading, a terrible workaround is to use React Hook Form’s setError on the input onChange event and set the error manually. The problem with this is that it causes re-render at root level and is likely to cause performance issues when the error is set if you have a large array.

REPLACE PART OF TEXT INSIDE A JSON FILE [closed]

I’m working in local with Javascript & Php, and I need to replace an object inside a json file, or at least get this object from my JS script.

My JSON file

I tried to use a regex but it doesn’t work.

function getParamsFromFile() {
fetch('./files/storage_game3_forSTACK.json', { cache: "no-store" })
.then(response => {
    response.text()
    .then( data => {  
        console.log(data);          

        const regExp = new RegExp("^/{.*?"6482515245115".*}/$")

        if (regExp.test(data)) {
            console.log('MATCHES : YES');
        }
        else {
            console.log('MATCHES : NO');
        }
    })
})        

}

Can you help me ?
Thx