How to make axios request call on every page in react?

I have Django and react app and I have to show some image as a campaign depending on current url.

On each page, there will be axios get request call to api and react will receive image and show the image on top.

to implement this I created function

let path_name = window.location.pathname;

const CampaignImageFetch = (url) => {
  if (!url) return "";
  return async () =>
    await axios({
      method: "get",
      url: process.env.REACT_APP_BASE_URL + "campaignpopup" + path_name,
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((res) => {
        return res;
      })
      .catch((e) => {
        return e;
      });
};

To implement this on every page, I have to call this function from every page and will have to load Image component on every page.
Is there any way I can implement this without adding the code on every page?

Chart.js annotation plugin – Box not being displayed correctly

I’m using [email protected] and [email protected] in a Vue 2 project. I was able to build a chart with a line but the box is always expanded out to the edges, I’m not sure if the issue is related with my x-axis, since the values are strings (months).

import Chart from 'chart.js';
import AnnotationPlugin from 'chartjs-plugin-annotation';

Chart.plugins.register(AnnotationPlugin);

new Chart(lineChart.value, {
    type: 'line',
    data: {
      labels: [
        'January',
        'February',
        'March',
        'April',
        'May',
        'June',
        'July',
      ],
      datasets: [
        {
          label: 'Dataset 1',
          data: [120, 125, 128, 121, 130, 125, 135],
          borderColor: '#018572',
          backgroundColor: 'green',
          lineTension: 0.1,
          fill: false,
        },
        {
          label: 'Dataset 2',
          data: [81, 85, 88, 90, 83, 82, 80],
          borderColor: '#9F642C',
          backgroundColor: 'brown',
          lineTension: 0.1,
          fill: false,
        },
      ],
    },
    options: {
      title: {
        display: true,
        text: 'Chart.js Line Chart',
      },
      legend: {
        display: true,
        position: 'top',
        labels: {
          boxWidth: 80,
          fontColor: 'black',
        },
      },
      annotation: {
        annotations: [
          {
            drawTime: 'afterDraw',
            id: 'a-line-1',
            type: 'line',
            mode: 'horizontal',
            scaleID: 'y-axis-0',
            value: '25',
            borderColor: 'red',
            borderWidth: 2,
          },
          {
            type: 'box',
            drawTime: 'beforeDatasetsDraw',
            id: 'a-box-1',
            xScaleID: 'x',
            xMax: 'July',
            xMin: 'January',
            yScaleID: 'y',
            yMax: 140,
            yMin: 120,
            backgroundColor: 'green',
          },
        ],
      },
    },
  });

This is the result that I’m always getting:

I need to decrease the box in the y-axis since I need to show two bands in the chart.
I’ll really appreciate any help and suggestions.

Using DataTables in PHP can’t change page on certain mobile browsers

Let me start by saying web development is not my thing so this was put together from snippets of code found online. I am not ashamed to say that. But it works beautifully on desktop. Does exactly what I need it to. I have Android devices. On Chrome (my default browser) and Edge, I can’t change pages on the DataTable when the setting is for 50 or 100 entries per page. My particular JSON file has over 5,600 entries so I really want/need to display 100 entries at a time. On Firefox, Dolphin and Opera I am able to change pages just like on desktop. No problems there. It works as intended on Apple iOS Safari on a tablet. So really, it comes down to Chrome and Edge. I can really let go of Edge compatibility, but Chrome is default on Android for a lot of people. Below is the entirety of the code. It’s only 55 lines not counting the dependencies of course.

<?php
//index.php
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Nemo's Setlist</title>
    <style type="text/css">
        body
        {
            font-family: Times New Roman;
            font-size: 12pt;
        }       
    </style>
  <link rel="stylesheet" href="https://cdn.datatables.net/1.13.4/css/jquery.dataTables.min.css" />
  <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
  <script src="https://cdn.datatables.net/1.13.4/js/jquery.dataTables.min.js"></script>  
  <style>
  .box
  {
   max-width:600px;
   width:100%;
   margin: 0 auto;;
  }
  </style>
 </head>
 <body>
  <div class="container">
   <br />
   <center><img src="header.jpg" alt="Nautilus Presents: Nemo's Setlist" title="Nautilus Presents: Nemo's Setlist"><br>
    <a href="http://www.keepitfishy.com/setlist/setlist.pdf"><img src="download.png" alt="Click Here to Download Setlist PDF" title="Click Here to Download Setlist PDF"></a><br><br></center>
   <div class="table-responsive">
    <table id="example" class="display" style="width:100%">
        <thead>
            <tr>
                <th>Artist</th>
                <th>Song</th>
                <th>Vocal Parts</th>
                <th>Duration</th>
            </tr>
        </thead>        
    </table>
   </div>
  </div>
<br>
<center>Copyright © TrojanNemo, 2023</center>
 </body>
</html>
<script>
$(document).ready(function () {
    $('#example').DataTable({
        ajax: 'setlist.json',
    'pageLength': 100});
});
</script>

I’ve tried making sure that the code is clean, nothing is left opened, I’ve tried playing with the pageLength value but I really need 100 to make it workable, tried my best Google-fu to find a solution. Nothing. I would love your help with this. Thank you!

How to best write live data packages to a file while preserving their order in NodeJS?

I am connected to a live stream where data packages arrive every couple of milliseconds. Every time a package comes in, a callback function is evoked to handle the data.

function handleData(data) {
   // efficient code to write data packages to a text file
   // while preserving the order in which they arrived
}

I want to log all the data to a file while retaining the order in which the packages arrived. Given the speed at which the data comes in, it can be assumed that lots of new packages arrive before the write operation is complete. How could I best do this? Are asynchronous IO functions suitable for this?

JavaScript fetch post of form to server returns undefined in most browsers. Only Firefox works fine

I’m trying to do a simple form post of a formdata object with the fetch API for my car club. It works in Firefox on Windows but not reliably in Chrome or Edge and Chrome on Android and iPhone always returns undefined. On desktop Chrome and Edge frequently return undefined but work sometimes. I suspected Code wasn’t waiting for the response and inserted waits but this did not solve the problem. Here’s the current ver: https://hcca.org/membership5b0.php

I have a function, checkit(), that checks for errors and tries to do the fetch if no errors. Its definition is:
async function checkit(form)

First line puts the form in a var, since script wasn’t posting I’m declaring form instead of using form pointer passed in:
form = document.getElementById(‘membershipForm’);

Then form is checked for errors

If no error, I try fetch. I read that return false doesn’t work to cancel fetch so tried to implement a cancel routine, but took it back out as I thought that was reason for thening:

const formData = new FormData(document.getElementById('membershipForm'));
let url = "membership-BE-2023.php";
document.getElementById('upload').innerHTML = "Processing your Credit Card & Membership. <img src='pics/spinner.gif' />";
fetch("membership-BE-2023.php", {
    method: "POST",
    body: formData
})
    // RETURN SERVER RESPONSE AS TEXT
.then((result) => {
    if (result.status != 200) { throw new Error("Bad Server Response"); }
        return result.text();
})
// SERVER RESPONSE
.then((response) => {
alert("1015 serv res=n"+response);
    console.log(response);
    parts = response.split("-||-");
    tranID= parts[0];
    thank = parts[1];//---than you msg
      // log response to the console so we can see
      //console.log(response); 
    grecaptcha.reset();

response just has undefined

As stated above fetch returns undefined in most browsers.

How can I send a message to a discord webhook through a browser console

I’m trying to make code that can send a message to a discord webhook through a browser console but I can’t get it to work

I tried this, as well as some reddit threads and reading the docs

fetch('https://discord.com/api/webhooks/WEBHOOK_ID/WEBHOOK_TOKEN', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    content: 'hello world'
  })
});

I’m getting a POST 400 error but i cant for the life of me figure out why
(Yes im using an actual URL when i try the code)

Delete an item in localStorage after reload

I have store all the item/tasks in localStorage.setItem('saved', newd[0].innerHTML) as the createTask function is executed so when the page reloads, if is not deleted than it remains saved. What I want is to be able to delete that single item as removeButton is clicked without affecting other items. It works before the page reloads but if more that one task is created, since all get store under the same saved name in localStorage, all get deleted. How could I delete the selected one without affecting the other items and still be able to do it after reloading the page?

let ids1 = document.getElementById('ids')
let ids2 = document.getElementById('ids2')

let buttonCreateTask = document.getElementsByClassName('create')
let newd = document.getElementsByClassName('newd')

let prevContent = localStorage.getItem('saved');
if (prevContent) { newd[0].innerHTML = prevContent}

function createTask (){ 

let paro = document.createElement('p')
paro.innerText = ids1.value + 'n' + ids2.value

let removeButton = document.createElement('button')
removeButton.innerHTML = 'REMOVE' 

paro.appendChild(removeButton)

removeButton.onclick = function() {
    paro.remove()
    localStorage.removeItem('saved')
   
}

if(ids1.value !== ''){ 
    if(ids2.value !== ''){ 
        
        newd[0].appendChild(paro)
ids1.value = ''
ids2.value = ''

localStorage.setItem('saved',  newd[0].innerHTML) 

    }else {
       alert('mising description')
    }
}else {
     alert('misning value')
}

buttonCreateTask[0].addEventListener('click', createTask )

enter image description here

enter image description here

Webgl FrameBuffer depth buffer is not clearing

I’m making a 2D sprite renderer, where the sprites draw to a render texture to allow for custom compositing. The issue is that for some reason the depth buffer on the FrameBuffer is not clearing, causing all the sprite to erase a permanent “streak,” across all the tiles that are behind them. Basically the same thing that happens when you forget to clear a color buffer, just instead of color the tiles in front streak like an eraser.

Setup code for frame buffer object

constructor(gl: WebGL2RenderingContext, width: number, height: number, depthBuffer = false){
    this._gl = gl;
    this._texture = this._gl.createTexture()!;
    this._frameBuffer = this._gl.createFramebuffer()!;

    this._gl.bindTexture(this._gl.TEXTURE_2D, this._texture);
    this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, this._frameBuffer);
    this._gl.framebufferTexture2D(this._gl.FRAMEBUFFER, this._gl.COLOR_ATTACHMENT0, this._gl.TEXTURE_2D, this._texture, 0);

    this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, this._gl.LINEAR);
    this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
    this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);

    if (depthBuffer){
        console.log("This logs out, so I know it gets created")
        this._depthBuffer = this._gl.createRenderbuffer();
        this._gl.bindRenderbuffer(this._gl.RENDERBUFFER, this._depthBuffer);
        this._gl.renderbufferStorage(this._gl.RENDERBUFFER, this._gl.DEPTH_COMPONENT16, width, height);
        this._gl.framebufferRenderbuffer(this._gl.FRAMEBUFFER, this._gl.DEPTH_ATTACHMENT, this._gl.RENDERBUFFER, this._depthBuffer);
    }

    this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
}
setAsRenderTarget(): void {
    this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, this._frameBuffer);
}

unsetRenderTarget(): void {
    this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, null);
}

And here’s the render code

render(): void {
    this._gl.useProgram(this._program);
    this._outputTexture.setAsRenderTarget();
    
    this._gl.clearColor(0, 0, 0, 0);
    this._gl.clear(this._gl.COLOR_BUFFER_BIT | this._gl.DEPTH_BUFFER_BIT);

    this._gl.enable(this._gl.DEPTH_TEST);
    this._gl.depthFunc(this._gl.LEQUAL);
    this._gl.depthMask(true);

    //render each atlas as a draw call
    for (let i = 0; i < this._atlasPool.length; i++){
        //gets atlas buffer and draws instanced arrays
        //no depth/frame/render buffer related code
    }

    this._gl.disable(this._gl.DEPTH_TEST);
    this._gl.depthMask(false);

    this._outputTexture.unsetRenderTarget();
}

I know it’s a depth buffer clearing issue, because if I resize the depth buffer before rendering (which basically creates a new depth buffer every frame) then everything seems to work perfectly, but obviously I don’t want to be doing that.

It looks like the buffer should be clearing, so is there anything that stands out that I’m doing wrong?

gl.readPixels only returns 0s for every point I clicked

So i have an animation where the small colorful small circles are growing.
enter image description here

I wish to access the RGB value of the point where my mouse clicks.

I tried two ways to present the x,y. one is in [-1,1]. The other way is the original values. But none of them worked.

I skipped some codes in the main function as they are not relevant to the click function.

var VSHADER_SOURCE =
'attribute vec4 a_Position;n' +
'uniform float u_SizeChange;n' +
'void main() {n' +
'  gl_Position.x = u_SizeChange * a_Position.x;n' +
'  gl_Position.y = u_SizeChange * a_Position.y;n' +
'  gl_Position.z = u_SizeChange * a_Position.z;n' +
'  gl_Position.w = 1.0;n' +
'}n';

var FSHADER_SOURCE =
'precision mediump float;n' +
'uniform vec4 u_FragColor;n' +
'void main() {n' +
'  gl_FragColor = u_FragColor;n' +
'}n';
function main() {
  var canvas = document.getElementById('webgl');

  // Get the rendering context for WebGL
  var gl = getWebGLContext(canvas);
  if (!gl) {
    console.log('Failed to get the rendering context for  WebGL');
    return;
  }

  // Initialize shaders
  if (!initShaders(gl, VSHADER_SOURCE, FSHADER_SOURCE)) {
    console.log('Failed to intialize shaders.');
    return;
  }    
var tick = function() {
  canvas.onmousedown = function(ev){click(ev,canvas,random_location,gl);};
  gl.clearColor(0.0, 0.0, 0.0, 1.0);
  gl.clear(gl.COLOR_BUFFER_BIT);   

  draw_circle(gl, 0, 0, disk_radius/400,[1.0,1.0,1.0,1.0]);
  if (game_running==true){requestAnimationFrame(tick, canvas);}      
};
        
  tick();
  
} }

function click(ev,canvas,random_location,gl) {
  var x = ev.clientX; // x coordinate of a mouse pointer
  var y = ev.clientY; // y coordinate of a mouse pointer
  var rect = ev.target.getBoundingClientRect() ;

  x = ((x - rect.left) - canvas.width/2)/(canvas.width/2);
  y = (canvas.height/2 - (y - rect.top))/(canvas.height/2);

  var x = ev.clientX - canvas.offsetLeft;
  var y = ev.clientY - canvas.offsetTop;
  const pixel = new Uint8Array(4);
  gl.readPixels(x, y, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  console.log(x,y);
  console.log(pixel);
  for (var i=0; i<=random_location.length;i++){
    // bacteria_alive[i]=false;
    if (bacteria_alive[i]==false){continue;}
    distance_to_center = cal_distance(x,y,0+disk_radius*Math.sin(random_location[i])/400,0+disk_radius*Math.cos(random_location[i])/400);  

    if (distance_to_center < radius/400){
      bacteria_alive[i]=false;
      break;

    }
  }

  }

Cypress/JavaScript: Parameter on request path (response.body.VARIABLE)

Was trying to figure out how to pass a variable on a response path like this

response.response.body.data.groupsData.hereGoesTheVariable

Where the variable is one of the attributes like name, id, etc. This way I can create a function and just pass the desire attribute.

I was trying template literals and so but with no affect. Any idea?

I’m getting the response from

 cy.wait('@' + alias).then(response => {
const text = response.response.body.data.groups.attribute; });

When i access a react-router route directly via url, it redirects to the ‘/’ route

Whenever i access the /projects route via url, it redirect to ‘/’, but i can access it via a button for example.
I am 100% sure its something wrong with the AuthContext, because if i just put true on the condition arg on PrivateRoute component, it works, but if the condition come from the AuthContext, its buggy

This is my Router component:

// private route, if condition is true, it render the children component, else, redirect to 'redirectRoute'
function PrivateRoute({condition, redirectRoute = '/login'}) {
    const auth = useAuth();
    if(auth.loading) return null;
    return (
        condition ? <Outlet></Outlet> : <Navigate to={redirectRoute}></Navigate>
    )
}

function Router() {
    // this useAuth() is basically a useContext(AuthContext)
    const auth = useAuth();

    return (
        <BrowserRouter>
            <Routes>
                <Route exact path="/" element={<PrivateRoute condition={auth.isLogged}></PrivateRoute>}>
                    <Route exact path="/" element={<Home></Home>}></Route>
                </Route>
                <Route exact path="/projects" element={<PrivateRoute condition={auth.isLogged}></PrivateRoute>}>
                    <Route exact path="/projects" element={<Projetos></Projetos>}></Route>
                </Route>
            </Routes>
        </BrowserRouter>
    );
}

And this is my AuthContext.js:

export const AuthContext = createContext({});

export function AuthProvider({children}) {
    const [isLogged, setIsLogged] = useState(false);
    const [loading, setLoading] = useState(false);

    useEffect(() => {
        // this function send the jwt token to backend to verify if its valid, if so, it do a setIsLogged(true)
        async function checkToken() {
            const token = JSON.parse(localStorage.getItem('costs_token'));
            if(!token) return false;
            const headers = {
                'Content-Type': 'application/json',
                authorization: 'Bearer '+token
            }

            const response = await fetch('/auth/validatetoken', {
                method: 'GET',
                headers
            });

            if(response.status === 200) {
                setIsLogged(true);
                return true;
            }
            localStorage.removeItem('costs_token');
            return false;
        }

        setLoading(true);
        checkToken().then(() => setLoading(false));
    }, []);

    return (
        <AuthContext.Provider value={{isLogged, loading}}>{children}</AuthContext.Provider>
    );
}

I tried using a boolean value that do not come from AuthContext, it worked, but if the boolean come from the AuthContext, i can’t access it directly via url, it rediret me to ‘/’.

Why do I still keep geting [object Promise] instead of the actual text? [duplicate]

I have this test function that keeps returning the text “[object Promise]” instead of the actual text value returned by the function. What am I doing wrong?

async function test()
{
  const url = 'http://backend:5000/api'
  const response = await fetch(url);
  return await response.text()
}`

I have tried various alternatives such as using Promise..Then etc but still can’t get it to work.

Next.js slow performance with static html exprt

I have a simple one page app built with Next.js and mui. There’s no real js dependency after page is rendered.

I want to export the app to a static html file using Next’s feature Static HTML Export

When I deploy the app regularly (e.g. with node js) the lighthouse performance score is 99. When I export the page to static html the score goes down to 80. The biggest problem is Total Blocking Time.

Because the web app is static, I edited the final HTML and deleted all script tags, so no javascript is loaded. 99% of the site still works fine (only one popover doesn’t work) and now the performance score is 99.

Is there anything I can do to improve page load with static html? It feels like there should be some easy config to load the js in a way that will not block performance.

I tried changing all script tags to load async or defer and the score went up to 82, which I also found surprising because I’d expect defer to be similar to deleting the scripts when it comes to performance

page performance
enter image description here

React-PDF: How to pan and clear canvas?

I am trying to provide pan functionality as well as the ability to clear the page when annotations are made with https://github.com/wojtekmaj/react-pdf. I am using https://codesandbox.io/s/react-typescript-zoom-pan-html-canvas-p3itj?from-embed=&file=/src/index.tsx by robinovitch61’s work as my basis for panning.

However, I can’t seem get the canvas to pan. Is this because the canvas is not “draggable”?

Also, when I draw annotations and use .clearRect() it makes the whole canvas black rather than just clearing the shapes. Is there a way to re-render the same page to act as a “clear” function?

Thanks!

Mongoose findByIdAndRemove() function doesn’t seem to work?

When checking the checkbox with a /POST method to the server, it passes the item’s ID back to the script.

Then I try to call the findByIdAndRemove() function but it doesn’t seem to actually delete the document.

I’m checking with Mongosh (MongoDB new Shell).

NODE:

app.post('/delete', function(req, res){

  const checkedItem = req.body.checked;

  Item.findByIdAndRemove(checked);
  
});

EJS:

<% newListItems.forEach(function(item){ %>

      <form action="/delete" method="post">

        <div class="item">
          <input type="checkbox" onChange="this.form.submit()" name='checked' value='<%= item._id %>'>
          <p> <%=item.name%> </p>
        </div>

      </form>


    <% }); %>

‘Test’ should be deleted when checked: https://i.stack.imgur.com/ujL7Z.png

But ‘Test’ is still intact: https://i.stack.imgur.com/vomkW.png

With the most recent Mongoose upgrade to version 7.0, they removed callbacks and some methods stoped working the way they did.

I’ve tried reading their docs about async and await, using .then and .catch and found no help on the open web since the update is recent.