Apollo Client is not using cached data and instead makes a network request

I have this weird behavior that I’ve been wrapping my head around for the past couple of hours.

Let’s consider these two queries as examples:

A query that returns and array of authors

query Authors {
  authors {
    id
    name
    books {
      code
      name
    }
  }
}

and another query that returns a single author

query Author($id: ID!) {
  author(id: $id) {
    id
    name
    books {
      code
      name
    }
  }
}

In my UI, imagine we map through the list of authors and render a card for each author. When you click on the card, it redirects you to a new page that has data for the author you clicked on, thus also triggering the Author query with an id.

Although I would expect the data for the single author to be retrieved from the cache ( since we’ve already called the Authors query ), it makes a network request for the single Author query. The really weird part is, if I remove the books fields from both queries and repeat the steps above, no network request is being made for a single author and the data is retrieved from the cache, as it should.

This leads me to believe that there is something wrong with how books are identified by code instead of id similar to author so I added a type policy for it. Here is how my apollo cache looks like:

const cache = new InMemoryCache({
  typePolicies: {
    Book: {
      keyFields: ["code"],
    },
  },
});

If I also manually inspect the cache, the book appears like so:

Book:{"code":"123"}: { __typename: 'Book', code: '123', name: 'Some name' }

which seems to be alright, but still I cannot wrap my head around why when I add the books field back to both queries and I request data for a single author, instead of taking the data from the cache, a network request is made.

I would really appreciate the help as I’ve been going in circles for the past couple of hours.

DELETE fetch react js

i need help here i cant delet my date from mongodb i think theres problem with the server.

this error come everytime i press delet button,

i can add date to my mongodb but i can delet date

it can find the id but cant connect to the server for delert

the error App.js:45

DELETE http://localhost:3000/s/5 404 (Not Found)


import "./App.css"; import { Table } from "./components/Table"; import { Modal } from "./components/Modal";

function App() {   const [modalOpen, setModalOpen] = useState(false);   // start code to recive date from our API system   const [rows, setRows] = useState([
    {
      date: "",
      description: "",
      status: "",
      cantidad: ""
    }   ]);

 useEffect (()=>{   fetch("/s").then(res=> { 
    if(res.ok) {
      return res.json()
    }
    }).then(jsonRes => setRows(jsonRes));   },[]);  // we can  put [] for stoping fetch to load alot of data https://stackoverflow.com/questions/56926282/react-hooks-fetch-wont-stop-fetching  // end code to recive date from our API system

  const [rowToEdit, setRowToEdit] = useState(null);

     const handleDeleteRow = (targetIndex) => {    fetch(`/s/${targetIndex}`,  
      {method: "DELETE",
        })
    .then((response)=>{
    if(!response.ok){
        throw new Error("net no work");
      }
       return response.json();   })   .then(()=>{
    setRows(rows.filter((_, idx)=>  idx !==targetIndex));
       })
    .catch((error)=> console.log("error dele:", error));
   
    };
      const handleSubmit = (rows) => {
    rowToEdit === null
      ? setRows([rows])
      : setRows(
          rows.map((currRow, idx) => {
            if (idx !== rowToEdit) return currRow;

            return rows;
          })
        );   };

  return (
      <div> <h1 className="h1">Control de Helados</h1>
      <div className="App">
      <Table rows={rows} deleteRow={handleDeleteRow} editRow={handleEditRow} />

      <button onClick={() => setModalOpen(true)} className="btn">
        Add
      </button>

      {modalOpen && (
        <Modal
          closeModal={() => {
            setModalOpen(false);
            setRowToEdit(null);
          }}
          onSubmit={handleSubmit}
          defaultValue={rowToEdit !== null && rows[rowToEdit]}
        />

      ) }
      
    </div>
    </div>   ); }

export default App; ```

React App Shows White Screen After Adding New Routes

I’m working on a React application and recently added new routes to my App.jsx file. However, after adding these routes, my application only shows a white screen. When I remove the new code, the landing page displays correctly again.

Here is the relevant excerpt from my App.jsx file:

import Landing from './landing';
import Login from './login';
import {
  BrowserRouter as Router,
  Route,
  Switch
} from 'react-router-dom';

const Main = () => {
  return (
    <Router>
      <Switch>
        <Route path="/landing" exact component={Landing} />
        <Route path="/login" component={Login} />
      </Switch>
    </Router>
  );
};

export default Main;

I’ve checked the following:

I get this error:

[plugin:vite:import-analysis] Failed to resolve import “./landing” from “src/App.jsx”. Does the file exist?

I’ve restarted the development server.
There are no typos or case sensitivity issues in the import statements.
Despite these checks, the white screen persists. What could be causing this issue, and how can I resolve it?

What I Expected:

I expected the application to navigate to the Landing component when accessing "/landing" and to the Login component when accessing "/login".

What Actually Happened:

After adding the new routes, the application only shows a white screen. When I remove the new code, the landing page displays correctly again.

Tabulator js: properly show nested arrays as coulmns which could be searchable

I have a json data such as below that I want to generate a table using tabulator js like picture1 below. I followed the documentation to implement nested data, so I changed the data to correct format and pass the other object of the nested arrays to _children property, but the picture 2 has been generated. (dataTree: true,dataTreeStartExpanded: true, passed as options)

[
  {
    id: 1,
    name: "john",
    phone_numbers: [
      {title: "cell", phone_number: "123-456-789"},
      {title: "home", phone_number: "987-654-321"},
      {title: "office", phone_number: "987-654-321"},
    ],
    locations: [
      {title: "home", code: 123, address: "us"},
      {title: "office", code: 321, address: "canada"},
    ]
  },
  {
    id: 2,
    name: "alex",
    phone_numbers: [
      {title: "cell", phone_number: "123-456-789"},
      {title: "home", phone_number: "987-654-321"},
    ],
    locations: [
      {title: "home", code: 123, address: "us"},
      {title: "office", code: 321, address: "canada"},
    ]
  },
]

picture1
picture2

I will be pleased if you you have any idea to generate this which the nested arrays could be treat as a normal column …

Reflowable column-grid-based gallery layout question (example link)

I’ve been interested in making a little portfolio website thingy for myself that utilizes a similar sort of grid as the website linked. I have very little knowledge related to CSS and website building in general, so I’m really struggling with wrapping my head around the way things are organized there.

It appears to be using custom JS code alongside a 7-column grid to reflow and place content based on the viewfinder measurements, which I think is supported by the way absolute positions are assigned to each of the block elements. What exactly is the purpose for the grid JS stuff? Could there be a known and more accessible alternative to doing that? I apologize for not getting proper knowledge before asking this; however, I am very interested in knowing the inner workings now of all times. Assume I know nothing about JS.

Joi Validation Schema Conditional Logic Not Working as Expected Based on Dynamic Value

I am having trouble with a Joi validation schema where the validation logic needs to handle different version ranges dynamically. The version ranges for legacy and current reports are defined in a configuration object, and I need the validation to adapt based on these ranges.

The validation schema does not seem to work correctly even though isLegacyReport and isCurrentReport functions return appropriate boolean values. I suspect there might be an issue with how these functions are integrated into the Joi when conditions.

export const reportValidator = {
    params: Joi.object({
        version: Joi.string()
            .required()
            .pattern(/^v[1-9]d*$/)
    }),
    body: Joi.object({
        end_date: Joi.date().required(),
        start_date: Joi.date().required(),
        org_id: Joi.number().when(Joi.ref('/params.version'), {
            is: Joi.string().custom((value) => isCurrentReport(value)),
            then: Joi.required(),
            otherwise: Joi.forbidden()
        }),
        state_id: Joi.number().when(Joi.ref('/params.version'), {
            is: Joi.string().custom((value) => isCurrentReport(value)),
            then: Joi.required(),
            otherwise: Joi.forbidden()
        }),
        zone_id: Joi.array().items(Joi.number().required()).when(Joi.ref('/params.version'), {
            is: Joi.string().custom((value) => isCurrentReport(value)),
            then: Joi.required(),
            otherwise: Joi.forbidden()
        }),
        office_id: Joi.array()
            .items(Joi.number().required())
            .when(Joi.ref('/params.version'), {
                is: Joi.string().custom((value) => isLegacyReport(value)),
                then: Joi.required(),
                otherwise: Joi.forbidden()
            })
    })
};

Webshop with API call after successful payment [closed]

I am developing Custom Studies for Sierra Chart’s ACSIL framework. Let’s call them programs from now on and I want to redistribute them. See the working of that here: https://www.sierrachart.com/index.php?page=doc/AdvancedCustomStudyInterfaceAndLanguage.php#Redistributing.

I want to create a webshop where I can sell these Studies. The client side is simple, it should list the available programs. The payment will be done with Stripe. After a payment is successful, I want to make an API call to the Sierra Chart WebAPI, to redistribute the programs automatically.
The Sierra Chart WebAPI is located here: https://www.sierrachart.com/index.php?page=doc/WebAPI.php.

I am new to web development, what technologies should I use?
I would be the happiest, if there is an already existing solution out there, where I can automate what should happen after a successful payment, is there any?

Bundling for “Isolated Worlds” in Chrome Browser Extension

I’m thinking about how I can structure my code.

Since some code in Chrome Browser runs in “Isolated Worlds”, little VMs, I have trouble bundling my Javascript without creating a lot of duplicated code.

For my browser extension, I want to add a listener, that has a callback function someFunctionToUnpack.

// typescript
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
  if (message.action === 'DO_STH') {
    chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
      const tab = tabs[0];
      if (tab && tab.id !== undefined) {
        chrome.scripting.executeScript({
          target: { tabId: tab.id as number },
          func: someFunctionToUnpack,
        });
      }
    });
  }
});

Ideally, it contains code that I can re-use in other places, because I do need this code in other places.

// typescript
import { some } from "anotherFile.ts";

const someFunctionToUnpack = ()=> {
  return some.objectContainingFunctions();
}
const doSomthingWithA = (a)=> {
  console.log(a);
}

const someFunctionToUnpack() {
  const a = anotherFunctionCall()
  doSomethingWithA(a);
}

If I did that, my current settings compile in a way that object() of some is not defined.

// In the VM, which has got the callback and
// is now isolated from the rest of the compiled javascript:
(()=>{
  const e = (()=>{
    const e = {
      some.objectContainingFunctions() // breaks here
    };
    console.log(e);
  })()
}
)()

While in a normal environment, we would bundle everything to the absolut minimum, I
require some code to be fully unpack and intentionally be duplicated, so that callback from event listeners in Chrome extensions can have access to their references, while I still avoid writing duplicated code.

Because it breaks in the VM, I’m forced to copy and move code into the someFunctionToUnpack and create duplicated code.

I’m using Webpack 5

module.exports = {
  entry: {
    'service-worker': './src/service-worker.ts',
    'content': './src/content.ts',
    'index': './src/backend/index.ts',
  },
  output: {
    path: path.resolve(__dirname, 'out'),
    filename: '[name].js',
    clean: true
  },
  resolve: {
    extensions: ['.ts', '.js', '.json']
  },
  module: {
    rules: [
      {
        test: /.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /.json$/,
        type: 'javascript/auto',
        loader: 'json-loader'
      }
    ]
  },
  plugins: [
    new HtmlWebpackPlugin({
        template: './src/index.html',
        filename: 'index.html',
        chunks: ['index'],
      }),
    new CopyWebpackPlugin({
      patterns: [
        { from: 'src/manifest.json', to: 'manifest.json' },
        { from: 'src/icons', to: 'icons' },
        { from: 'src/styles', to: 'styles' },
      ]
    })
  ],
  optimization: {
    minimize: true,
    minimizer: [new TerserPlugin({
      terserOptions: {
        compress: true,
        mangle: true
      }
    })],
  },
};

How to execute a Python script which uses a library which produces a visualization in a Angular JS dashboard?

I’m trying to figure out the best way to integrate Python code and render the output onto an Angular dashboard.

Here is the library I’d like to execute in Python and then take the rendered output and place it into a Angular JS dashboard: https://robert-haas.github.io/gravis-docs/index.html

The library is called Gravis and this rendering can be outputted in several ways such as using gv.vis(), gv.d3(), fig.display(), fig.export_html(), as well as export to svg and others. I’m trying to figure out what is the most optimal way to do this with Angular Javascript or just JS in general.

Here is an example Python code that outputs a Gravis visualization:

import gravis as gv
graph1 = {
    'graph':{
        'directed': True,
        'metadata': {
            'arrow_size': 5,
            'background_color': 'black',
            'edge_size': 3,
            'edge_label_size': 14,
            'edge_label_color': 'white',
            'node_size': 15,
            'node_color': 'white',
        },
        'nodes': {
            1: {'metadata': {'shape': 'rectangle', 'y': 200}},
            2: {},
            3: {},
            4: {'metadata': {'shape': 'rectangle', 'y': 200}},
            5: {'metadata': {'shape': 'hexagon', 'y': 0}},
        },
        'edges': [
            {'source': 1, 'target': 2, 'metadata': {'color': '#d73027', 'de': 'Das',   'en': 'This'}},
            {'source': 2, 'target': 3, 'metadata': {'color': '#f46d43', 'de': 'ist',   'en': 'is'}},
            {'source': 3, 'target': 1, 'metadata': {'color': '#fdae61', 'de': 'das',   'en': 'the'}},
            {'source': 1, 'target': 4, 'metadata': {'color': '#fee08b', 'de': 'Haus',  'en': 'house'}},
            {'source': 4, 'target': 3, 'metadata': {'color': '#d9ef8b', 'de': 'vom',   'en': 'of'}},
            {'source': 3, 'target': 5, 'metadata': {'color': '#a6d96a', 'de': 'Ni-.',  'en': 'San-'}},
            {'source': 5, 'target': 2, 'metadata': {'color': '#66bd63', 'de': 'ko-',   'en': 'ta'}},
            {'source': 2, 'target': 4, 'metadata': {'color': '#1a9850', 'de': 'laus.', 'en': 'Claus.'}},
        ],
    }
}

gv.d3(graph2, use_node_size_normalization=True, node_size_normalization_max=30,
      use_edge_size_normalization=True, edge_size_data_source='weight', edge_curvature=0.3)`

Is it possible to call this Python script with all its libraries and take than output and display it through an Angular dashboard?

Thank you

I tried PyScript but the libraries it supports are limited. I’ve been experimenting with Flask and Django but have limited knowledge of integration that with Angular Javascript.

Health probe with errors in Azure Container App

I have an application running nodejs and redis services. The exposed port is only 3000. This application is an api that queries and stores data in a postgresql.
The services run in a single container.
My problem is that when I check the system log, I keep getting liveness, readiness and startup errors, even though I already have them configured.
So I wanted to know if anyone has had this problem and how to solve it.
I have the ingress type enabled and http type.
Another important thing to mention is that this application will be receiving approximately 150,000 requests per day.
Thanks!

This is the configuration I currently have:

Configuration of health probes

My Dockerfile

FROM node:21.4-bookworm

RUN apt-get update && 
    apt-get install -y iputils-ping traceroute telnet dnsutils git nano htop redis-server && 
    npm install -g pm2 && 
    ln -fs /usr/share/zoneinfo/America/Santiago /etc/localtime && 
    rm -rf /var/lib/apt/lists/*

RUN echo "user1:password" | chpasswd

RUN adduser -u 2000 user2 && 
    echo "user2:password" | chpasswd

WORKDIR /usr/src/app/CUA-Tunel

COPY . .
    
EXPOSE 3000

COPY entrypoint.sh /entrypoint.sh

RUN chmod +x /entrypoint.sh

ENTRYPOINT ["/entrypoint.sh"]

My entrypoint

#!/bin/bash

# Configuración DNS
echo search server01.domain.com > /etc/resolv.conf
echo search server02.domain.com >> /etc/resolv.conf
echo "nameserver xxx.xxx.xxx.xxx" >> /etc/resolv.conf
echo "nameserver xxx.xxx.xxx.xxx" >> /etc/resolv.conf

echo "maxclients 500000" >> /etc/redis/redis.conf

npm install

/etc/init.d/redis-server start

npx pm2 start ecosystem.config.js --no-daemon

My compose

#version: '2.0'

services:
  tunel-nodejs:
    build:
      context: .
      dockerfile: Dockerfile
    ports:
      - "3000:3000"

How to intercept API response of a webRequest in Chrome Extension?

I’m a little new to Chrome Extension Development. The plan is to intercept response of a specific API call. I was able to filter the specific API call using chrome.webRequest API. To be more specific, I am using chrome.webRequest.onCompleted. Now the problem is I am unable to get the api response in the callback function of the event listener. Someone on the github pages suggested to add requestBody in extraInfoSpec. But now I’m getting error, the control never reaches in the callback function. Could you please help me understand what am I missing here?

chrome.webRequest.onCompleted.addListener(
  async (details) => {
    // console.log(details.url)
    if (
      details.url.indexOf('voyager/api/graphql') !== -1 &&
      details.url.indexOf('profileUrn') !== -1
    ) {
      console.log(details)
    }
  },
  {
    urls: ['*://www.example.com/*'], // changed it for the obvious reasons
  },
  ['requestBody']
)

I tried a few things I found on the internet.

Expected: I need the API response in the event listener callback. I don’t want to use debugger API, as it shows a warning. And that’s not a good UX.

How to get dynamic value from Json file generated during execution and use it in next command for Jenkins pipeline?

I have a Script which is generating a Dynamic session_id in a json file and after execution of script I want to use that session_id in next command like for example below is JSON file


   "name": "TestName",
   "session_id": "51a2ce15-2caf-47e8-9415-405d623b4fb3"
   
}

I want to save it in a variable SessionID(or any other name) and then want to use in a command like below

npm run test --session_id %SessionID%

I have found a tool Jq which is used to play with JSON file, I installed it on my windows server.

And then in Jenkins step I’m trying to execute batch script for jq

steps {
                script {
                     bat "jq .session_id sessionFile.json > out.tmp"
                     bat "set /p SessionID=<out.tmp"
                     echo "%SessionID%"
                     bat "npm run test --session_id %SessionID%"
                }
            }

But getting jq is not recognised error in jenkins console log.

Then I tried manually to login on server and Executed command
jq .session_id sessionFile.json > out.tmp
It’s working fine as ADMIN user

C:/USERS/AUT >>  jq .session_id sessionFile.json > out.tmp

but for Jenkins as its running as C:ProgramDataJenkins.jenkinsworkspaceOrderCreation
So Tried command

C:ProgramDataJenkins.jenkinsworkspaceOrderCreation> jq .session_id sessionFile.json > out.tmp

It’s returning ‘Access is Denied’ reponse.

Can anyone please guide how to resolve the issue? OR s there any other alternative solution to handle this Problem?

Google cloud storage return old images

I have a public bucket, uploading the images through a React web app using a signed url:

export const uploadFile = (policy: PostPolicy, file: File): Promise<void> => {
  const formData = new FormData();

  for (const field in policy.fields) {
    const value = policy.fields[field];
    value && formData.append(field, value);
  }
  formData.append("file", file);

  return fetch(policy.url, {
    method: "POST",
    body: formData,
  }).then();
};

The PostPolicy is the result of the call to bucket.GenerateSignedPostPolicyV4. The upload and retrieving work, but once the image is updated, the browser seems to cache the old file, for a long time, and I am not able to edit this caching. I already tried´to user the gcloud-cors-settings adding maxAgeSeconds:

[
  {
    "maxAgeSeconds": 10,
    "method": ["POST", "GET"],
    "origin": ["http://localhost:50030"],
    "responseHeader": ["Content-Type", "Cache-Control"]
  }
]

Did not help. I tried to add the ‘Cache-Control’ header:


export const uploadFile = (policy: PostPolicy, file: File): Promise<void> => {
  const formData = new FormData();

  for (const field in policy.fields) {
    const value = policy.fields[field];
    value && formData.append(field, value);
  }
  formData.append("file", file);

  const headers = new Headers();
  headers.append("Cache-Control", "public, max-age=15");

  return fetch(policy.url, {
    method: "POST",
    headers: headers,
    body: formData,
  }).then();
};

I don’t get any error, but the header is ignored.

How can I fix this problem?

How to check if two lists have the same content in JavaScript [duplicate]

let list1 = ["abc", 85, true];
let list2 = ["abc", 85, true];

if (list1 == list2) {
  document.write("Works");
}
else {
  document.write("Doesn't work");
}

Both arrays are literally the same in every way, yet the program writes out

“Doesn’t work”

How do I check if they are the same?

Thanks in advance.

I tried doing != and === instead of ==, but it still wrote out doesn’t work.

vercel doesn’t render an image properly

i deployed my app to vercel, using nextjs and tailwind.

here i have a navbar, and as a bottom border of nav i need to use image as a border instead of normal border created with css.

Here’s how it looks on localhost:
border bottom as an image in localhost

and that’s how it looks in vercel:
border bottom as an image in vercel

in the console in both localhost and vercel i’m getting the same error: Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

if you need the code, here’s implementaion of border bottom as an image:

*navbar*

<div className="relative">
        <Image
          src="/assets/images/navUnderline.png"
          alt="navbar underline"
          width={10}
          height={10}
          className="absolute bottom-0 left-0 w-full -z-10" // Full width and positioned at the bottom
        />
</div>

an image contains in public folder