How to store JSON in variable from fetch API

I can’t disclose the URL and what API I’m using because it breaches my work’s policy but hopefully I can provide enough information for assistance. I have a javascript function that runs on a on-click (I’m eventually building up a form that will make use of this fetch).

function getdata() {
let customer_po = document.getElementById("customer").value;
let access_token;
let data = {
    'grant_type': 'REDACTED'
}
let state = {
    "state": "REDACTED"
}
fetch(prod_auth, {
    method: "POST",
    headers: login_header,
    body: new URLSearchParams(data),
})
    .then(response => response.json())
    .then(result => console.log(result))

}

This works and I can access the JSON dictionary in the console. However, when I try to use my access_token variable declared earlier in such a way:

.then(response => response.json())
.then(result => {access_token = result["access_token"];})

and console.log(access_token) gives undefined. I need to access this variable in my getdata() function so it can be used as a parameter in another fetch call. Any help would be appreciated. Thank you!

Creating like button for multiple items

I am new to React and trying to learn more by creating projects. I made an API call to display some images to the page and I would like to create a like button/icon for each image that changes to red when clicked. However, when I click one button all of the icons change to red. I believe this may be related to the way I have set up my state, but can’t seem to figure out how to target each item individually. Any insight would be much appreciated.

`
 //store api data
 const [eventsData, setEventsData] = useState([]);

 //state for like button
 const [isLiked, setIsLiked] = useState(false);

useEffect(() => {
 axios({
  url: "https://app.ticketmaster.com/discovery/v2/events",
  params: {
    city: userInput,
    countryCode: "ca",
  },
  })
  .then((response) => {
    setEventsData(response.data._embedded.events);
  })
  .catch((error) => {
    console.log(error)
  });
});

//here i've tried to filter and target each item and when i 
console.log(event) it does render the clicked item, however all the icons 
change to red at the same time
  const handleLikeEvent = (id) => {
   eventsData.filter((event) => {
     if (event.id === id) {
       setIsLiked(!isLiked);
     }
    });
  };

return (
   {eventsData.map((event) => {
        return (
          <div key={event.id}>
              <img src={event.images[0].url} alt={event.name}></img>
              <FontAwesomeIcon
                 icon={faHeart}
                 className={isLiked ? "redIcon" : "regularIcon"}
                 onClick={() => handleLikeEvent(event.id)}
               />
          </div>
)

  `

 

Is it possible to tell if an async function is currently running at the top of the stack?

I’m trying to do something that involves a global context that knows about what function is running at the moment.

This is easy with single-threaded synchronous functions, they start off running and finish running when they return.

But async functions can pop to the bottom of the stack and climb back up multiple times before completing.

let currentlyRunningStack: string[] = [];
function run(id: string, cb: () => any) {
  currentlyRunningStack.push(id);
  cb()
  currentlyRunningStack.shift();
}

// works with synchronous stuff
run("foo", () => {
  run("bar", () => console.log("bar should be running"));
  console.log("now foo is running");
});

// can it work with asynchronous
run("qux", async () => {
  // async functions never run immediately...
  await somePromise();
  // and they start and stop a lot
});

Is it possible to keep track of whether or not an asynchronous function is currently running or currently waiting on something?

Jquery cannot find newly added elements [duplicate]

The Context

To make the explanation of my issue easier, I have created a small example:

Let’s say we have this simple website (index.html):

<!DOCTYPE html>
<html lang="en">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <body>
        <script id="navigation" src="nav.js"></script>
        <p>Amazing website content</p>
        <script src="something.js"></script>
    </body>
</html>

Let’s say the nav.js script imports our navigation bar from a nav.html into our index.html, so the script would look something like this:

fetch('nav.html')
    .then(res => res.text())
    .then(text => {
        let oldE = document.querySelector("script#navigation");
        let newE = document.createElement("div");
        newE.innerHTML = text;
        oldE.parentNode.replaceChild(newE,oldE);
    })

and for simplicity sake our “navigation bar” (nav.html) looks like this:

<ul class="class-nav">
  <li><a href="#">Home</a></li>
  <li><a href="#">News</a></li>
  <li><a href="#">Contact</a></li>
  <li><a href="#">About</a></li>
</ul>

Finally, we have something.js which is a javascript that uses jQuery to do some stuff, for now, we just want to be able to print out elements with the class name class-nav:

jQuery(document).ready(function($) {
    "use strict";
    var magic = function() {
        $('.class-nav').each(function() {
            console.log(this);
        });
    };
    magic();
});

The Issue

If I hardcoded my navigation bar (nav.html) to the webpage (index.html), the magic() function in something.js (that uses jQuery) works and is able to print out the navigation bar class-nav.

However, if we have it in the current setup, where we have our navigation bar added to the webpage from a separate nav.html file, the magic() function isn’t able to find class-nav.

Why? And how can I modify something.js to be able to retrieve class-nav using jQuery?

How to make these fixed cols’ width on a Bootstrap 4.0 table-responsive?

I’ve been trying to get this one to work based on similar questions/answers, but no success.

This is my attempt to fix the col width by explicitly setting each column’s width, but nothing changes!

<thead style="white-space: nowrap">
                <tr>
                  <th style="width: 1%" class="text-center">ClientID</th>
                  <th style="width: 2%" class="text-center">Task Nº</th>
                  <th style="width: 25%" class="text-center">Task</th>
                  <th style="width: 4%" class="text-center">Date Assigned</th>
                  <th style="width: 4%" class="text-center">Link To File</th>
                  <th style="width: 22%" class="text-center">Notes</th>
                  <th style="width: 14%" class="text-center">Approval</th>
                  <th style="width: 26%" class="text-center">Comments</th>
                </tr>
              </thead>

Here’s the Fiddle if you feel like giving a hand. Thank you!

Here’s

How to change the font in Algolia’s autocomplete?

I’m using Algolia’s autocomplete feature, which is working fine, but how can I change the font of the text shown in the autocomplete results? I’m using Javascript / JQuery

I would like to use a custom font (Cera) that I use in the rest of my website (which I’m loading via @font-face)

$('.algolia').autocomplete(
            var1,
            var2,
            var3,
            var4,
        )

TypeError: Cannot read properties of undefined (reading ‘create’). Happens when running npm run build:ssr

Getting an error when running npm run build:ssr to try to deploy my angular application
See the code below that the error is pointing to.
I’ve been trying to figure out why is giving me that error for weeks now.

const webpack = require('webpack');
const WebpackConfigFactory = require('@nestjs/ng-universal')
  .WebpackConfigFactory;

module.exports = WebpackConfigFactory.create(webpack, {
  // Nest server for SSR
  server: './server/main.ts'
});

Sort array in alphabetic order without using Array.sort in Java

I want to sort values of an array in alphabetic order, using merge sort. I have this code so far, but I when I run it, the output is jumbled and not in correct order. (Charlottetown, Fredericton, Montreal, Toronto, Vancouver, …)

If anyone has any advice/solutions, I would appreciate your help 🙂

Here is my current code.

    class Main {
  public static void main(String[] args) {
    String [] words = {"Montreal", "Halifax", "Toronto", "Vancouver",
              "Whitehorse", "Winnipeg", "Calgary", "Edmonton", 
              "Hamilton", "Regina", "Saskatoon", "Sault Ste. Marie", "Moncton", "Gander", "Fredericton", "Charlottetown"};
   for(int i = 0; i < words.length; i++)
{
    int smallest = i;
    for(int j = i + 1; j < words.length; j++) 
    {
        if(words[j].compareTo(words[i]) < 0)
            smallest = j;
    }
    
    String aux = words[i];
    words[i] = words[smallest];
    words[smallest] = aux;
}
for(int i = 0; i < words.length; i++)
{
    System.out.println(words[i]);
}
  }
}

Render a razor component in a new browser tab and pass a list of objects to it

I’m trying to create a control that opens a razor component and displays the objects sent to the page after a user clicks a Print button. Using the IJSRuntime.InvokeAsync() the blank page opens to a blank component page but the objects are not being captured.
Here is the button onclick event-

    public async Task PrintViewableOrderPackingSlips()
    {
        OrdersToPrint = OrdersToPack.Where(o => o.IsOrderVisible).ToList();        

        await IJS.InvokeAsync<object[]>("open", "/PrintPackingSlip", "_blank", new object[]{ OrdersToPrint });   


    }

That invokes this razor component page

@layout Blazing_Fruit.Pages.BlankLayout

@page "/PrintPackingSlip"


<body onload="window.print()">

    <Div>print page</Div>  
          

</body>


@code{


    [Parameter]
    public JsonContent orders { get; set; }

    [Parameter]
    public List<UnshippedOrder> value { get; set; }

    
}

Obviously I’m not capturing the object passed over because I get this error in the originating page

Uncaught (in promise) TypeError: cyclic object value

and this error in the new component window

Uncaught (in promise) Error: Found malformed component comment at Blazor:{“sequence”:0,”type”:”server”,”prerenderId”:”aa8c4268d131416eb85784e2fcf8549f”,”descriptor”:

How can I pass my list of objects to the new component?

Skip starting blank rows in Excel with XLSX in JavaScript Sheet-JS

I have the following code that works great when the header row is row 1

  readerData(rawFile) {         
      return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.onload = e => {
          const data = e.target.result;
          const workbook = XLSX.read(data, { type: "array" });
          const firstSheetName = workbook.SheetNames[0];
          const worksheet = workbook.Sheets[firstSheetName];
          const header = this.getHeaderRow(worksheet);
          const results = XLSX.utils.sheet_to_json(worksheet,{ header: 0, range: 0, defval: ""});
          this.generateData({ header, results });
          this.loading = false;
          resolve();
        };
        reader.readAsArrayBuffer(rawFile);
      });
    },
    generateData({ header, results }) {
      this.excelData.header = header;
      this.excelData.results = results;
      this.excelData.original_results = [...results];
      this.onSuccess && this.onSuccess(this.excelData);

         var grid = this.$refs.membersGrid.ej2Instances;                         
        grid.dataSource = this.excelData.results;
          grid.refresh(); 
    },
      getHeaderRow(sheet) {
      const headers = [];
      const range = XLSX.utils.decode_range(sheet["!ref"]);
      let C;
      const R = range.s.r;
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })];
        /* find the cell in the first row */
        let hdr = "UNKNOWN " + C; // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell);
        headers.push(hdr);
      }
      return headers;
    },

It works great and put all of the Header values into the excelData.header and it put all of the named array data into the excelData.results. My problem is it all goes to a mess when the first row or first two rows are blank or I need to skip them. I’ve tried

  https://github.com/SheetJS/sheetjs/issues/463

but I’m using “xlsx”: “^0.17.1” . When I used

    range.s.r = 1;

I was able to change my range to A2 but I could not get my named array of data. Any help is appreciated .

I’m trying to access to my get method with the route api/products and it throws me this error, what could be the cause?

THIS IS THE ERROR

[Error: ENOENT: no such file or directory, open ‘C:UsersUsuarioDesktopproductos.txt’] {
errno: -4058,
code: ‘ENOENT’,
syscall: ‘open’,
path: ‘C:UsersUsuarioDesktopproductos.txt’
}

[on screen it only shows me an empty obj or nothing directly]

[INDEX.JS]

const express = require("express");
const app = express();
const http = require("http").Server(app);
const fs = require("fs").promises;
const path = require("path")
const routes = require("./routes");
const io = require("socket.io")(http);
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

app.set("view engine", "ejs");
app.use(express.static(path.join(__dirname, "public")));
app.set("views", "./views");
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  fs.readFile("productos.txt", "utf-8");
  res.render("form");
});

app.post("/productos", async (req, res) => {
  fs.readFile("productos.txt", "utf-8")
    .then((data) => {
      const type = JSON.parse(data);
      const newProduct = {
        id: nanoid(),
        ...req.body,
      };
      type.push(newProduct);
      fs.writeFile("productos.txt", JSON.stringify(type));
      res.render("productos", {
        type,
      });
    })
    .catch((err) => {
      if (!req.body.title && !req.body.price && !req.body.thumbnail) {
        res.status(400).json({
          error: "Bad Request",
          message: "Title, price and thumbnail are required",
        });
      }
      console.log(err);
    });
});

app.get("/productos", (req, res) => {
  fs.readFile("productos.txt", "utf-8").then((data) => {
    res.render("productos", {
      type: JSON.parse(data),
    });
  });
});

routes(app);

const port = 8080;
app
  .listen(port, () => {
    console.log(`App listening on port ${port}!`);
  })
  .on("error", (err) => {
    console.log(err);
    throw err;
  });

[API.JS]

const fs = require("fs").promises;
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

class Productos {
  constructor(txtNameFile) {
    this.txtNameFile = txtNameFile;
    this.productos = [];
  }

  async fileInJSON() {
    let fileTxt = await fs.readFile(this.txtNameFile, "utf-8");
    let type = JSON.parse(fileTxt);
    return type;
  }

  async fileSaving(item) {
    let type = JSON.stringify(item);
    await fs.writeFile(this.txtNameFile, type);
  }

  async obtenerProductos() {
    try {
      const productos = await this.fileInJSON();
      return productos;
    } catch (error) {
      console.log(error);
    }
  }

  async obtenerProducto(id) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      return producto;
    } catch (error) {
      console.log(error);
    }
  }

  async create(data) {
    try {
      // create and adding product using fs module system
      const newProduct = {
        id: nanoid(),
        ...data,
      };
      this.productos.push(newProduct);
      await this.fileSaving(this.productos);
      return newProduct;
    } catch (error) {
      console.log(error);
    }
  }

  async eliminarProducto(id) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      const index = productos.indexOf(producto);
      productos.splice(index, 1);
      await this.fileSaving(productos);
    } catch (error) {
      console.log(error);
    }
  }

  async actualizarProducto(id, data) {
    try {
      const productos = await this.fileInJSON();
      const producto = productos.find((producto) => producto.id === id);
      const index = productos.indexOf(producto);
      productos[index] = {
        ...producto,
        ...data,
      };
      await this.fileSaving(productos);
      return productos[index];
    } catch (error) {
      console.log(error);
    }
  }
}

module.exports = Productos;

[ROUTES/PRODUCTOSROUTER.JS]

const express = require("express");
const Productos = require("../api");
const router = express.Router();
const itemService = new Productos("../productos.txt");

router.get("/", async (req, res) => {
  res.json(await itemService.obtenerProductos());
});

router.post("/", async (req, res) => {
  if (!req.body.title && !req.body.price && !req.body.thumbnail) {
    res.status(400).json({
      error: "Bad Request",
      message: "Title, price and thumbnail are required",
    });
  }
  const producto = itemService.create(req.body);
  res.json(await producto);
});

router.get("/:id", async (req, res) => {
  const producto = itemService.obtenerProducto(req.params.id);
  if (producto) {
    res.json(await producto);
  } else {
    res.status(404).json({ error: "Producto no encontrado" });
  }
});

router.put("/:id", async (req, res) => {
  const id = req.params.id;
  const producto = itemService.actualizarProducto(id, req.body);
  res.json(await producto);
});

router.delete("/:id", async (req, res) => {
  const id = req.params.id;
  itemService.eliminarProducto(id);
  res.json({ message: "Producto eliminado" });
});

module.exports = router;

[ROUTES/INDEX.JS]

const productosRouter = require("./productosRouter");

function routes(app) {
  app.use("/api/productos", productosRouter);
}

module.exports = routes;

How can I use querySelectorAll with htmx

I am working with htmx which is a fantastic library, I have a little problem that’s not very clear on how to solve. htmx uses queryselector to locate elements to swap/update example with hx-swap="...", hx-target="..." how do I do a querySelectorAll. example I have a class bookmark, when a user bookmarks a post, I want to update all the classes with .bookmark

How to make a simple count down timer from milliseconds with Javascript/REACT

I’m wondering the best way to make a simple minute/second countdown timer to next refresh. This component’s prop get updated every 5 minutes and counts down until the next refresh per second. This seems to get out of sync pretty quickly. Any thoughts?

I’m not sure if timeRemaining < 0 makes sense — if we subtract 1000 from 1100 we would have 100 (how do I account for that?) I’m hoping there’s a better way. Should I convert this back to seconds?

Thanks for any feedback.

...

const CountdownToNextRefresh = ({milliToNextRounded5Min}) => {
  const [, setCount] = useState(0);
  const [timeRemaining, setTimeRemaining] = useState(milliToNextRounded5Min);

  useEffect(() => {
    const oneSecond = 1000;
    const interval = setInterval(() => {
      setCount((prevCount) => prevCount + 1);
      setTimeRemaining(timeRemaining < 0 ? milliToNextRounded5Min : timeRemaining - oneSecond);
    }, oneSecond);
    return () => clearInterval(interval);
  }, [timeRemaining, milliToNextRounded5Min]);

  function msToTime(milliseconds) {
    // Get hours from milliseconds.
    const hoursFromMilli = milliseconds / (1000*60*60);
    const absoluteHours = Math.floor(hoursFromMilli);
    const h = absoluteHours > 9 ? absoluteHours : `0${absoluteHours}`;

    // Get remainder from hours and convert to minutes.
    const minutesfromHours = (hoursFromMilli - absoluteHours) * 60;
    const absoluteMinutes = Math.floor(minutesfromHours);
    const m = absoluteMinutes > 9 ? absoluteMinutes : `0${absoluteMinutes}`;

    // Get remainder from minutes and convert to seconds.
    const seconds = (minutesfromHours - absoluteMinutes) * 60;
    const absoluteSeconds = Math.floor(seconds);
    const s = absoluteSeconds > 9 ? absoluteSeconds : `0${absoluteSeconds}`;

    return h === "00" ? `${m}:${s}` : `${h}:${m}:${s}`;
  }

return (<div>{msToTime(timeRemaining)}</div>)
}