Iterating same function over multiple object paramaters – error after first iteration

I’m trying to write a piece of code that will run output the results of a function “recipeGen()” multiple times for each member of an object.
The code I have written can output the name of each member of the object I want to effect if told to log to console, but will only run the desired function once before giving me an “uncaught typeError”
How can I change this so that my code outputs “recipeGen()” for every sub member of “recipes”?

Thanks in advance for any help.

p.s. the recipes object I am using is larger than the one posted here but in exactly the same format all the way through. In current state my code will output recipeGen() for the first member “roastRosemaryPotatoes” and give the error when attempting to run the function for the next object.

p.p.s I have also tried using 2 x for/in loops with the same result, hence the Object.keys usage in the second half of function

function outputAllRecipes() {
  for (type in recipes) {
    console.log(type)
    let recipeArray = Object.keys(recipes[type])
    console.log(recipeArray)
    for (let i = 0; i < recipeArray.length; i++) {
      recipeGen(recipes[type][recipeArray[i]])
    }
  }
}

function recipeGen(recipe) {
  let output = `<div class="recipe-box">`
  output += `<h3>${recipe.name}</h3>`
  output += `<div class="ingredient-list"><h4>Ingredients:</h4>`
  output += listIngredArray(recipe) + `</div>`
  output += `<h4>Method:</h4>`
  output += recipe.method + `</div>`
  console.log(output)
  return output
}

let recipes = {
  side: {
    roastRosemaryPotatoes: {
      name: "Roast Rosemary Potatoes",
      serves: 2,
      ingredients: [
        ['potato', 3],
        ['rosemary', 1],
        ['oliveOil', 30],
        ['saltPepper', 0]
      ],
      method: `<ol>
                    <li> Preheat oven to 180 degrees</li>
                    <li> Cut potatoes in to bite sized chunks</li>
                    <li> In a large bowl, toss the potatoes, rosemary, salt and pepper untill evenly coated</li>
                    <li> Roast at 180 for ~20 minutes, then turn oven up to 220 degrees and roast for a further 15 - 20 minutes</li>
                    <li> Serve</li>
                    </ol>`
    },
    mashedPotAndsweetPotato: {
      name: "Mashed Potato and Sweet Potato",
      serves: 2,
      ingredients: [
        ['potato', 2],
        ['sweetPotato', 1],
        ['butter', 25],
        ['saltPepper', 2]
      ],
      method: `<ol>
                    <li> Roughly dice the potato and steam in a steamer until tender (15 - 20 minutes)</li>
                    <li> In a large bowl, add the potatoes, butter and salt and pepper to the potatoes and mash with a potato masher in to a puree.
                    (if you do not have a potato masher, you can use a fork, or a wooden spoon but the result will be quite lumpy. I like potatoes this way but YMMV)</li>
                    <li> Serve</li>
                    </ol>`
    }
  }
}

How do I overlay an image over a canvas

I have a canvas that shows matrix binary code raining down. I would like to add an image over the canvas in question

This is what I have

<div class="rain">
            <canvas id="Matrix"></canvas>
             <div class ="imgclass">
                <img class="imgclass" src="assets/image.jpg"/>
            </div>
        </div>

JavaScript for the canvas

const canvas = document.getElementById('Matrix');
const context = canvas.getContext('2d');

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const latin = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
const nums = '0123456789';

const alphabet = latin + nums;

const fontSize = 16;
const columns = canvas.width/fontSize;

const rainDrops = [];

for( let x = 0; x < columns; x++ ) {
    rainDrops[x] = 1;
}

const draw = () => {
    context.fillStyle = 'rgba(0, 0, 0, 0.05)';
    context.fillRect(0, 0, canvas.width, canvas.height);
    
    context.fillStyle = '#0F0';
    context.font = fontSize + 'px monospace';

    for(let i = 0; i < rainDrops.length; i++)
    {
        const text = alphabet.charAt(Math.floor(Math.random() * alphabet.length));
        context.fillText(text, i*fontSize, rainDrops[i]*fontSize);
        
        if(rainDrops[i]*fontSize > canvas.height && Math.random() > 0.975){
            rainDrops[i] = 0;
        }
        rainDrops[i]++;
    }
};

setInterval(draw, 30);

and the CSS:

.rain {
    background: black;
    height: 40%;
    overflow: hidden;
}

canvas {
    background-image: url("assets/img.jpg");
}

Right now the image in question appears below the canvas as opposed to on the canvas (ie. in the middle).

Using Firebase as backend vs coding own backend system – What’s better?

I’m aiming to build a calendar Flutter app, which offers user authentication. As I’m a total beginner if it comes to backend programming, I thought of using Firebase. However, while informing myself about it, I read that using Firebase has plenty disadvantages like:

  • data migration problems
  • pricing
  • limited querying capabilities

Hence I’m intending to learn more about REAL backend development and bumped into express, MongoDB and node.js, which was very interesting, especially for my project.
My problem though is that I would have to host my rest API with e.g Heroku, which is way too expensive for me, including the pricing for MongoDB. Furthermore, I’d have to build my own authentication system with JWT, of which I’m not sure if it can be as safe as Google’s Firebase. :/

Now my question is:
Do you guys think that Firebase is enough for my project, or is it cleverer to invest into MongoDB and Heroku? Other backend approaches are obviously welcome too! 🙂

After I refresh, the toggle text functionality is restored

To hide the unnecessary columns, I’m using a javascript toggle text on my gallery filter, which works flawlessly. However, the columns expand every time I refresh the page, and I have to click show all then hide all to get it to work. And the reason I did two rows is that if I insert the showmore id in the middle of the columns, after I press show all, they will display one column on each line, however in this method all the columns will display normally. I tried changing the display value in the java script to many other values, but it is still not working properly. Do you have any suggestions for how to resolve this?

  function togglesec1() {
    var showMoreText = document.getElementById("showmore");  
    var buttonText = document.querySelector("#moreBtn p");
    var moreIcon = document.querySelector("#moreBtn img");
    
    if (startsec.style.display === "none") {
      showMoreText.style.display = "none";
      startsec.style.display = "inline";
      buttonText.innerHTML = "Show More";    
      buttonText.classList.remove('lesser');
      moreIcon.classList.remove('lesser');
    } else {
      showMoreText.style.display = "inline";
      startsec.style.display = "none";
      buttonText.innerHTML = "Show Less";
      buttonText.classList.add('lesser');
      moreIcon.classList.add('lesser');
    }
  }
<head>
  <link rel="shortcut icon" href="./images/favicon.ico" type="image/vnd.microsoft.icon" />
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>    
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
</head>

<body>
<section id="work">
       <div class="container-fluid clientbox text-center py-5">
         <div class="row">
              <div class="col-12 col-md-12 col-lg-12 text-center">
         <ul>
           <li class="list-inline-item active" data-filter="all">A</li>
           <li class="list-inline-item" data-filter="B">B</li>
           <li class="list-inline-item" data-filter="C">C</li>
           <li class="list-inline-item" data-filter="D">D</li>
           <li class="list-inline-item" data-filter="M">M</li>
           <li class="list-inline-item" data-filter="UI">U</li>
           <li class="list-inline-item" data-filter="CO">CC</li>
         </ul>
        </div>
        </div>
          <div class="row g-0">

            <div class="clients C col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/book-11549420966kupbnxvyyl.png" alt="Logo">
                  <figcaption class="product-desc"><P>C</P></figcaption>
                  <figcaption class="product-desc2"><p>H</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B D C CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://w7.pngwing.com/pngs/36/268/png-transparent-ballpoint-pen-stylus-fountain-pen-waterman-pens-pen-pen-advertising-rollerball-pen.png" alt="Logo">
                  <figcaption class="product-desc"><P>b</P></figcaption>
                  <figcaption class="product-desc2"><p>k</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B C D M U CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/black-electric-guitar-11530936970df8gvueqvz.png" alt="Logo">
                  <figcaption class="product-desc"><P>n</P></figcaption>
                  <figcaption class="product-desc2"><p>P</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B C D CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/book-11549420966kupbnxvyyl.png" alt="Logo">
                  <figcaption class="product-desc"><P>B</P></figcaption>
                  <figcaption class="product-desc2"><p>G</p></figcaption>
                </figure>
              </a>
            </div>
            </div>
            <div id="startsec"></div>
            <div id="showmore">
            <div class="row g-0">
            <div class="clients B CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/black-electric-guitar-11530936970df8gvueqvz.png" alt="Logo">
                  <figcaption class="product-desc"><P>N</P></figcaption>
                  <figcaption class="product-desc2"><p>g</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients D B C M col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://w7.pngwing.com/pngs/454/512/png-transparent-red-and-white-guitar-red-white-guitar-red-guitar-folk-guitar-thumbnail.png" alt="Logo">
                  <figcaption class="product-desc"><P>N</P></figcaption>
                  <figcaption class="product-desc2"><p>s</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B UI col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://esquilo.io/png/thumb/OQQMxyuwyKmDwp0-Musical-Vector-Acoustic-Guitar-PNG.png" alt="Logo">
                  <figcaption class="product-desc"><P>BS</P></figcaption>
                  <figcaption class="product-desc2"><p>l</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/book-11549420966kupbnxvyyl.png" alt="Logo">
                  <figcaption class="product-desc"><P>CN</P></figcaption>
                  <figcaption class="product-desc2"><p>C</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients D col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/black-electric-guitar-11530936970df8gvueqvz.png" alt="Logo">
                  <figcaption class="product-desc"><P>d</P></figcaption>
                  <figcaption class="product-desc2"><p>T</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B D col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://w7.pngwing.com/pngs/454/512/png-transparent-red-and-white-guitar-red-white-guitar-red-guitar-folk-guitar-thumbnail.png" alt="Logo">
                  <figcaption class="product-desc"><P>Bl</P></figcaption>
                  <figcaption class="product-desc2"><p>E</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B D CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://toppng.com/uploads/preview/book-11549420966kupbnxvyyl.png" alt="Logo">
                  <figcaption class="product-desc"><P>BN</P></figcaption>
                  <figcaption class="product-desc2"><p>S</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B C D M col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://w7.pngwing.com/pngs/454/512/png-transparent-red-and-white-guitar-red-white-guitar-red-guitar-folk-guitar-thumbnail.png" alt="Logo">
                  <figcaption class="product-desc"><P>B</P></figcaption>
                  <figcaption class="product-desc2"><p>I</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B M C D CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://w7.pngwing.com/pngs/454/512/png-transparent-red-and-white-guitar-red-white-guitar-red-guitar-folk-guitar-thumbnail.png" alt="Logo">
                  <figcaption class="product-desc"><P>N</P></figcaption>
                  <div class="product-desc2"><p>o</p></div>
                </figure>
              </a>
            </div>
            <div class="clients C B col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHo3btqZiiOgTrKCGihDfnm9V5va87up2aeg&usqp=CAU" alt="Logo">
                  <figcaption class="product-desc"><P>CAG</P></figcaption>
                  <figcaption class="product-desc2"><p>Jr</p></figcaption>
                </figure>
              </a>
            </div>
            <div class="clients B col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHo3btqZiiOgTrKCGihDfnm9V5va87up2aeg&usqp=CAU" alt="Logo">
                  <figcaption class="product-desc"><P>Brl</P></figcaption>
                  <figcaption class="product-desc2"><p>Sl</p></figcaption>
                </figure>
              </a>
            </div>
          
            <div class="clients B CC col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHo3btqZiiOgTrKCGihDfnm9V5va87up2aeg&usqp=CAU" alt="Logo">
                  <figcaption class="product-desc"><P>Bn</P></figcaption>
                  <figcaption class="product-desc2"><p>SP</p></figcaption>
                </figure>
              </a>
            </div>
  
            <div class="clients B col-6 col-md-4 col-lg-3">
              <a href="#">
                <figure class="client-container">
                  <img class="img-fluid brand-img" src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSHo3btqZiiOgTrKCGihDfnm9V5va87up2aeg&usqp=CAU" alt="Logo">
                  <figcaption class="product-desc"><P>B</P></figcaption>
                  <figcaption class="product-desc2"><p>Wc</p></figcaption>
                </figure>
              </a>
            </div>
            </div>
          </div>
          <button onclick="togglesec1()" id="moreBtn">
            <p class="pink">Show More</p> 
            <img class="showmore" src="./images/load-more.png" alt="">
           </button>
        </div>  
      </section>
      <script src="https://cdn.jsdelivr.net/npm/@popperjs/[email protected]/dist/umd/popper.min.js" integrity="sha384-IQsoLXl5PILFhosVNubq5LC7Qb9DXgDA9i+tQ8Zj3iwWAwPtgFTxbJ8NT4GN1R8p" crossorigin="anonymous"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
      <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script>
      
      <script>$(document).ready(function (){$('.list-inline-item').click(function(){const value = $(this).attr('data-filter');if(value == 'all'){$('.clients').show('1000');}else{ $('.clients').not('.'+value).hide('1000');$('.clients').filter('.'+value).show('1000');}$(this).addClass('active').siblings().removeClass('active')})})</script>

      </body>

How to filter my json data by sector in handlebars using data-filter attribute?

Here is my HTML handlebar code, fetching data from JSON data, I can fetch all data from json, however, I would like to filter by sector and show them. Can we use data-filter attribute? How we could give an id to each object in json file?

    <li><a href="#" data-filter="*" class="active">All</a></li>
    <li><a href="#" data-filter=".coffe-rest">Coffee-Restaurant</a></li>
    <li><a href="#" data-filter=".bars">Bars</a></li>
    <li><a href="#" data-filter=".takeaway">Takeaway</a></li>
    <li><a href="#" data-filter=".residantial">Residantial</a></li>
    <li><a href="#" data-filter=".commercial">Commercial</a></li>

{{#each all_projects}}

{{title}}

{{/each}}

Also here is my jquery ;

$(document).ready(function() {

var projectTemplate = $("#project-template").html()

var compiledProjectTemplate = Handlebars.compile(projectTemplate);
var $projectList = $(".projects-feed")

var projectId = getParameterByName(“id”);
console.log(“project id: “, projectId)

$.ajax("data.json").done((project) => {
    if($("body").hasClass("project-details")) {
        $projectList.html(compiledProjectTemplate(project.projects[projectId]))
    } else {
        $projectList.html(compiledProjectTemplate(project))
    }

});

});

enter image description here
Thank you for all your answers..

React API call is going on multi loop inside a function

I am calling an API that is displaying ID and Name in the table. I want to perfor sorting. I am using Material UI table. When the handleTableChange function triggers the API call(apiCall) inside this function goes on loop.

In the handleTableChange function I am performing sorting on each column and showing the 10 records per page

What is the write approch to make this call?

function Schedules(props) {
    const [scheduleList, setScheduleList] = useState([]);
    const [totalSize, setTotalSize] = useState(0);
    const [sortQuery, setSortQuery] = useState("&sortDirection=desc");
    const [reqParams, setReqParams] = useState("?offset=0&limit=10");
    useEffect(() => {
        apiCall(reqParams + sortQuery);
    }, []);

    let apiCall = (reqParams) => { 
        schedules.getSchedule("/xxxx" + reqParams)
            .then((res) => {
                console.log(res, 'res schedule');
                if (res.data.metadata.outcome.status === 200) {
                    setScheduleList(res.data.data)
                    setTotalSize(res.data.totalCount)
                } else {
                    setScheduleList([])
                    setTotalSize(0)
                }
            })
    };

    const handleTableChange = (tableFactors) => {
            if (Object.keys(tableFactors).length === 0) {
                return;
            }
            const { recordsPerPage, currentPage } = tableFactors;
            //function for sort the columns
            let sortingQuery = "";
            if (tableFactors.sortData !== undefined) {
                for (const [key, value] of Object.entries(tableFactors.sortData)) {
                    if (value !== "default" && key.includes("sort")) {
                        sortingQuery += `&sort=${key.replace(
                            "sort",
                            ""
                        )}&sortDirection=${value}`;
                    }
                }
            } 

            // function for record per page
            var offset = 0;
            let limit = recordsPerPage || 10;
            if (currentPage) {
                offset = (currentPage - 1) * limit;
            }
            let reqPerPage = "?offset=" + offset + "&limit=" + limit;
            apiCall(reqPerPage + sortingQuery);
            setSortQuery(sortingQuery)
    }

    return (
            <div>
                <Table
                    id="scheduleGrid"
                    data={scheduleList}
                    totalSize={totalSize}
                    noDataText="No records found"
                    multisort={false}
                    columnResize
                    defaultSort={{ cret_ts: "desc" }}
                    columns={[
                        {
                            apiKey: "id",
                            columnText: "ID",
                            sort: true,
                            hidden: false,
                            filter: "text",
                        },
                        {
                            apiKey: "name",
                            columnText: "Name",
                            sort: true,
                            filter: "text",
                            hidden: false,
                        }, 
                    ]}
                    handleTableChange={handleTableChange}
                />
            </div> 
    );
}
export default Schedules;

“Http failure during parsing” NodeJS + Angular + CPanel

Service:

import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient } from '@angular/common/http';

constructor(
    private http: HttpClient
) { }

private API_GET_BARCO_BY_CANTIDAD = `${GlobalVariables.URL_NODE}/barco/encontrar/c/?barcosC=`;

private header = new HttpHeaders({
    'Content-Type': 'application/json'
});

public getBarcoByC(cantidad: Number): Observable<any> {
    return this.http.get<any>(this.API_GET_BARCO_BY_CANTIDAD + cantidad, { headers: this.header });
}

API:

const router = Router();
const Barco = require('../models/Barco')

router.get("/barco/encontrar/c/", getBarcosByC);

async function getBarcoBy(req, res) {
  try {
    let id = req.params.id;
    const barco = await Barco.findById(id, function (err, docs) {
      if (err) {
        console.log(`n[BarcosApi Error] Found Barco By Id(${id}):n`,err)
      } else {
        console.log(`n[BarcosApi] Found Barco By Id(${id}):n`, docs)
      }
    }).clone().catch(function (err) { console.log(err) })

    if ('err' in barco) return res.status(barco.codestatus).json(barco.err);
    return res.status(200).json(barco);
    
  } catch (err) {
    console.log("[BarcosApi] getBarcoByError", err);
  }
}

Console: temp0.error.text
Gives back the whole index.html page as error.text

All GET requests have the same respond(index.html), while POST, UPDATE, DELETE works flawlessly

How to mock Node’s worker_thread in Jest?

I have a worker_thread like this:

const worker = new Worker(path.resolve(__dirname, "worker.mjs"))
  .on("message", (data) => {
    this.date = data;
  });

Inside that worker.mjs, I run a REST API GET request, and some other formatting logic on the data retrieved.

and I want to mock it in Jest, I tried:

import path from "path";
import { MyModule } from "./MyModule";

describe("MyModule", () => {
  jest.mock(path.resolve(__dirname, "worker.mjs"));

  it("1st spec", () => {
    expect(1+1).toEqual(2)
  });
});

But when I run the test, jest doesn’t mock the worker, jest goes inside the worker code and actually executes the API call.

What is missing?

CSS HTML TABLE Row Drop Down Hidden

This should seem simpler. But I can’t find resolve online.

Just trying to have a new drop down row to enter some data on a form.
Should be simple. But the drop down shows in the first cell only.
Even when using colspan=5.

Or is there a better way? Thx for any help.

      <table cellspacing=0 cellpadding=7 border=1>
      <tr bgcolor=#efefef>
      <td></td>
      <td>Date</td>
      <td>DATA</td>
      <td>MORE DATA</td>
      <td>Method</td>
      </tr>
      <tr>
      <td>
      <button onclick="javascript:showElement('abcdata')" style="padding:4px" class=verd8> SHOW NEW ROW </button>
      </td>
      <td>Jan 22, 2022</td>
      <td>SOME DATA</td>
      <td>SOME MORE</td>
      <td>BUTTONDROP</td>
      </tr>
      <tr id="abcdata" style="display:none;"> 
      <td colspan=5>
      SHOW NEW ROW ACROSS ALL CELLS : sfdgsdfgs hlahhfa la dfl dfljhsd flhsd flhsdf lhdsfh asf alhd a</td>
      </tr>
      </table>

how to show posts by sub-categorys in react by json data?

I wanna make sub-categories and show the posts by these sub-categories. I follow this project to make it but here are one list category I need more categories like this which are nested by the first category as I want. I have some changes to the App.js file but I am not able to fix it.
When I create a sub-category in the JSON file does not show the category name and post details also. how to do it plz help me if you want.

This is the main project GitHub link

** Here My Changes Codes :**

App.js

import React, { useState } from "react";
import Data from "./Data";
import Card from "./Card";
import Buttons from "./Buttons";

const App = () => {
  const [item, setItem] = useState(Data);

  const menuItems = [
    ...new Set(Data.category?.map((Val) => Val.category.subcategory)),
  ];

  const filterItem = (curcat) => {
    const newItem = Data.category.filter((newVal) => {
      return newVal.category.subcategory === curcat;
    });
    setItem(newItem);
  };
  return (
    <>
      <div className="container-fluid">
        <div className="row">
          <h1 className="col-12 text-center my-3 fw-bold">
            Food Filtering App
          </h1>
          <Buttons
            filterItem={filterItem}
            setItem={setItem}
            menuItems={menuItems}
          />
          <Card item={item} />
        </div>
      </div>
    </>
  );
};

export default App;

Button.js

import React from "react";
import Data from "./Data";

const Buttons = ({ filterItem, setItem, menuItems }) => {
  return (
    <>
      <div className="d-flex justify-content-center">
        {menuItems.map((Val, id) => {
          return (
            <button
              className="btn-dark text-white p-1 px-2 mx-5 btn fw-bold"
              onClick={() => filterItem(Val)}
              key={id}
            >
              {Val}
            </button>
          );
        })}
        <button
          className="btn-dark text-white p-1 px-3 mx-5 fw-bold btn"
          onClick={() => setItem(Data)}
        >
          All
        </button>
      </div>
    </>
  );
};

export default Buttons;

Card.js

import React from "react";

const Card = ({ item }) => {
  return (
    <>
      <div className="container-fluid">
        <div className="row justify-content-center">
          {item.map((Val) => {
            return (
              <div
                className="col-md-4 col-sm-6 card my-3 py-3 border-0"
                key={Val.id}
              >
                <div className="card-img-top text-center">
                  <img src={Val.subimg} alt={Val.subtitle} className="photo w-75" />
                </div>
                <div className="card-body">
                  <div className="card-title fw-bold fs-4">
                    {Val.subtitle} &nbsp;&nbsp;&nbsp;&nbsp;--&nbsp;&nbsp;
                    {Val.subprice}
                  </div>
                  <div className="card-text">{Val.subdesc}</div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </>
  );
};

export default Card;

Data.js

const Data = [
  {
    id: "1",
    title: "Poha",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2021-08/loudr2go_aloo-poha_625x300_05_August_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
    desc: " Poha. Light, filling and easy to make, poha is one famous breakfast that is eaten almost everywhere in the country. And the best part is- it can be made in a number of ways. Kanda poha, soya poha, Indori poha, Nagpur Tari Poha are a few examples",
  },
  {
    id: "2",
    title: "Upma",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
    desc: " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
  },
  {
    id: "3",
    title: "Cheela",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://c.ndtvimg.com/2019-05/1afu8vt8_weight-loss-friendly-breakfast-paneer-besan-chilla_625x300_25_May_19.jpg?im=FaceCrop,algorithm=dnn,width=620,height=350",
    desc: "A staple across Indian households, moong dal is widely used in a number of Indian delicacies. One such delicacy is moong dal cheela. You can also add paneer to this recipe to amp up the nutritional value and make it, even more, protein-dense",
  },
  {
    id: "4",
    title: "Channa Kulcha",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-04/chana-kulcha_625x350_41429707001.jpg",
    desc: "A classic dish that never goes out of style. The quintessential chana kulcha  needs only a few ingredients - cumin powder, ginger, coriander powder, carom powder and some mango powder, which is what gives the chana it's sour and tangy taste.",
  },
  {
    id: "5",
    title: "Egg Curry",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-11/goan-egg-curry_620x350_41511515276.jpg",
    desc: "Eggs are a versatile food that can be cooked for any meal of the day. From breakfast to dinner, it can be a go-to food. Here is a mildly-spiced egg curry made with garlic, onions, a whole lot of kasuri methi, fresh cream, yogurt and fresh coriander.",
  },
  {
    id: "6",
    title: "Paneer Aachari",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-04/paneer_625x350_61429707960.jpg",
    desc: "Don't get intimidated by the list of ingredients because not only are already in your kitchen cabinet, but also because all they'll need is 20 minutes of your time. Chunks of cottage cheese cooked in some exciting spices, yogurt and a pinch of sugar.",
  },
  {
    id: "7",
    title: "Fish Fry",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_41434360207.jpg",
    desc: "Get your daily dose of perfect protein. Pieces of surmai fish marinated in garlic, cumin, fennel, curry leaves and tomatoes are pan-fried in refined oil and served hot. This fish fry recipe has a host of delectable spices used for marination giving it a unique touch.",
  },
  {
    id: "8",
    title: "Dum Alloo",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2015-06/indian-dinner_625x350_51434362664.jpg",
    desc: "Your family will thank you for this absolutely fantastic bowl of dum aloo cooked Lakhnawi style. Take some potatoes, crumbled paneer, kasuri methi, butter, onions and some ghee.",
  },
  {
    id: "9",
    title: "Malai Kofta",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg",
    desc: "A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious.",
  },
  {
    id: "10",
    title: "Malai Kofta",
    category: [
      {
        id: "2",
        subtitle: "Upma",
        subcategory: "Breakfast",
        subprice: "$1",
        subimg:
          "https://c.ndtvimg.com/2021-04/37hi8sl_rava-upma_625x300_17_April_21.jpg?im=FeatureCrop,algorithm=dnn,width=620,height=350",
        subdesc:
          " A quintessential South Indian Breakfast! Made with protein-packed urad dal and semolina followed by crunchy veggies and curd, this recipe makes for a hearty morning meal. With some grated coconut on top, it gives a beautiful south-Indian flavour.",
      },
    ],
    price: "$1",
    img: "https://i.ndtvimg.com/i/2017-10/makhmali-kofte_620x350_51508918483.jpg",
    desc: "A rich gravy made of khus khus, coconut and milk that tastes best with koftas made from khoya. This velvety and creamy recipe will leave you licking your fingers. Makhmali kofte can be your go-to dish for dinner parties as this is quite different from other kofta recipes and extremely delicious.",
  },
];

export default Data;

PDFkit (Node): How to create paragraph indents?

I’m trying to create paragraph indents in PDFkit. The PDFkit docs state that the indent attribute is “to indent each paragraph of text”. While trying this, only the first line has an indent.

const doc = new PDFDocument({ size: "A4" });
doc.pipe(fs.createWriteStream('output2.pdf'));
doc.addPage()
doc.text('fdgfdgfg fggfdgfdg fgfdg fdg dfgdfgdfg dfgfdg fgfgfdg fdgdfgdfg', { indent: 30 })
doc.end();

The code delivers an indent only in the first line of the paragraph. How can I indent the whole paragraph?

How to target a div using content inside the div

I have 2 divs with same class name but different strings inside the div. I want to use an insertAfter the first div to display some additional text, but the text is being displayed under both divs:

<div class='test'>First Div</div>
<div class='test'>Second Div</div >

My approach:


if(document.getElementsByClassName('test')[0] && document.getElementsByClassName('test')[0].inner
HTML == 'First Div') {
          $('<h2>Inserting New Text</h2>').insertAfter('.test')[0];
                     }

But this adds the text after both the First Div and the Second Div. I want to know if there is a way to insert only once or insert after matching the string