How to iterate over all children elements?

How to iterate over all children elements?

I have an array that has an infinite number of nested childrens, how do I output all of them?

const data = [
    { title: "Mark", children: [{ title: "Alex" }] },
    {
      title: "Alisa",
      children: [{ title: "Bob", children: [{ title: "Jacob" }] }]
    }
];

I only go through two levels, but there can be as many as you like.

{data.map((item) => {
        return (
          <div>
            {item.title}
            {item.children.map((item) => item.title)}
          </div>
        );
      })}

Handlebars: Access has been denied to resolve the property

I am having trouble with this web application. I can enter all the data on the main page but when I enter it doesn’t appear on the list page. When I go into MongoDB the data is being stored. I have attached the server.js file and the petController.js file. I have also attached a few images of what I am seeing. I know it is an issue with the handlebars package, but I can’t seem to figure it out.

**server.js file**

require('./models/db');

const express = require('express');
const path = require('path');
const exphbs = require('express-handlebars');
const hbs = require('express-handlebars');


const petController = require('./controllers/petController');

var app = express();
app.use(express.urlencoded({
    extended: true
}));
app.use(express.json());
app.set('views', path.join(__dirname, '/views/'));
app.engine('handlebars', exphbs.engine({ extname: 'handlebars', defaultLayout:'mainLayout', layoutsDir: __dirname + '/views/layouts/' /*hanldlebars: allowInsecurePrototypeAccess(Handlebars)*/ }));
app.set('view engine','handlebars');

app.listen(3000, () => {
    console.log('Express server started at port : 3000');
});

app.use('/pet', petController);

**petController.js**

const express = require('express');
var router = express.Router();
const mongoose = require('mongoose');
const Pet = mongoose.model('Pet');

router.get('/', (req, res) => {
    res.render("pet/addOrEdit", {
        viewTitle: "Insert Pet"
    });
});

router.post('/', (req, res) => {
    if (req.body._id == '')
        insertRecord(req, res);
        else
        updateRecord(req, res);
});


function insertRecord(req, res) {
    var pet = new Pet();
    pet.petName = req.body.petName;
    pet.breed = req.body.breed;
    pet.age = req.body.age;
    pet.owner = req.body.owner;
    pet.save((err, doc) => {
        if (!err)
            res.redirect('pet/list');
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("pet/addOrEdit", {
                    viewTitle: "Insert Pet",
                    pet: req.body
                });
            }
            else
                console.log('Error during record insertion : ' + err);
        }
    });
}

function updateRecord(req, res) {
    Pet.findOneAndUpdate({ _id: req.body._id }, req.body, { new: true }, (err, doc) => {
        if (!err) { res.redirect('pet/list'); }
        else {
            if (err.name == 'ValidationError') {
                handleValidationError(err, req.body);
                res.render("pet/addOrEdit", {
                    viewTitle: 'Update Pet',
                    employee: req.body
                });
            }
            else
                console.log('Error during record update : ' + err);
        }
    });
}


router.get('/list', (req, res) => {
    Pet.find((err, docs) => {
        if (!err) {
            res.render("pet/list", {
                list: docs
            });
        }
        else {
            console.log('Error in retrieving pet list :' + err);
        }
    });
});


function handleValidationError(err, body) {
    for (field in err.errors) {
        switch (err.errors[field].path) {
            case 'petName':
                body['petNameError'] = err.errors[field].message;
                break;
            case 'breed':
                body['breedError'] = err.errors[field].message;
                break;
            default:
                break;
        }
    }
}

router.get('/:id', (req, res) => {
    Pet.findById(req.params.id, (err, doc) => {
        if (!err) {
            res.render("pet/addOrEdit", {
                viewTitle: "Update Pet",
                pet: doc
            });
        }
    });
});

router.get('/delete/:id', (req, res) => {
    Pet.findByIdAndRemove(req.params.id, (err, doc) => {
        if (!err) {
            res.redirect('/pet/list');
        }
        else { console.log('Error in pet delete :' + err); }
    });
});

module.exports = router;

**Images**
[![enter image description here][1]][1]
[![enter image description here][2]][2]
[![enter image description here][3]][3]
[![enter image description here][4]][4]


  [1]: https://i.stack.imgur.com/NQUWg.png
  [2]: https://i.stack.imgur.com/9ZsCi.png
  [3]: https://i.stack.imgur.com/GVW4Q.png
  [4]: https://i.stack.imgur.com/muC2L.png

Extend the timeout after each click on react

Suppose there’s the following simple component. When I click on the button, the message will change to Clicked for 1 second and then goes back to -. However, when I spam the button, I want the title to be Clicked but it should go back to - after the last click of the button. Basically, I want each click to expand the timeout.

If this was a simple JS function, I would just clear the interval after each click and set another timeout. However, I’m not sure how to achieve the same result using react hooks.

import ReactDOM from 'react-dom';
import {useEffect, useState} from 'react';
import './index.css';

const Test = () => {
    const [message, setMessage] = useState("-");

    const buttonClick = () => {
        setMessage("Clicked");
    }
    useEffect(() => {
        if(message !== "-") {
            const id = setTimeout(() => {
                console.log("Running Interval");
                setMessage("-");
            }, 1000);

            return () => {
                console.log("Clearing Interval");
                clearTimeout(id);
            }
        }
    }, [message]);

    return (
        <article>
            <header>
                {message}
            </header>
            <button onClick={buttonClick}>button</button>
        </article>
    );
}

setInterval with 2 seconds delay [duplicate]

I’m doing a chronometer and everything is doing well and work it, however there is a little problem, It’s happenning a delay of 2 second when I click and call the function start(). After delay, chronometer starts without problems.
The code is right here:

let ss = 00;
let mm = 00;
let hh = 00;
let tempo = 1000;
let cron;

function timer() {
    let padrao = (`${hh <10? '0' + hh: hh}:${mm < 10? '0' + mm : mm}:${ss < 10? '0' + ss : ss}`); 
    document.getElementById('stopWatch').innerText = padrao;

    ss++;
    if (ss == 60) {
        ss = 0;
        mm++
    } else if (mm == 60) {
        mm = 0;
        hh++
    }

}

function start() {
    cron = setInterval(() => {timer();}, tempo);
    document.getElementById("run").disabled = true;
}
function pause() {
    clearInterval(cron); 
    document.getElementById("run").disabled = false;
}
function reset() {
    clearInterval(cron); 
    ss = 00;
    mm = 00;
    hh = 00;
    document.getElementById('stopWatch').innerText = '00:00:00';
    document.getElementById("run").disabled = false;
}

strong text

Next.js read Firestore data

I found this Next.js starter to read data in Firestore v9, but it shows data after onclick. In Next.js how would I write this to actually be consumable data without the click?

import { db } from '@/lib/firebase/initFirebase'
import { doc, getDoc } from "firebase/firestore"
import { useUser } from '@/lib/firebase/useUser'
import Button from 'react-bootstrap/Button'

const ReadDataFromCloudFirestore = () => {
    const { user } = useUser()
    const readData = async () => {
        try {
            const userDoc = doc(db, "myCollection", user.id)
            await getDoc(userDoc).then((doc) => {
                if (doc.exists()) {
                    console.log(doc.data())
                }
            })
            alert('Data was successfully fetched from cloud firestore! Close this alert and check console for output.')
        } catch (error) {
            console.log(error)
            alert(error)
        }
    }

    return (
        <div style={{ margin: '5px 0' }}>
            <Button onClick={readData} style={{ width: '100%' }}>Read Data From Cloud Firestore</Button>
        </div>
    )
}

export default ReadDataFromCloudFirestore

React: Is it possible to make things like buttons or text areas be part of the component code but then be omit when you want to use that component?

I have this form component that I created but in some cases I want it to have a button and in other cases I want it to have a text field instead of the input field like I have coded.

function FormTypeOne(props) {
  return (
    <form className={classes.form}>
      <div className={classes.control}>
        <label htmlFor={"title"}>{props.title}</label>
        <input type={props.type} required id={props.id} />
      </div>
    </form>
  )
}

Is it possible to add a button and a text field but then decide which one I want to use? Or do I need to make 3 different components?

If array includes a cetain key then delete entire object using JS

I am getting back a 2d array and sometimes I will get an “error” and “message” back for that particular object. The problem I keep running into, Is that the messaging I am getting back varies…How do I go about if the “error” key is mentioned then delete the object entirely.

My Array:

let filtData = [
  [
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "es",
        },
      },
    },
    {
      error: {},
      message: "Cannot read property 'attrs' of undefined"
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "sp",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "it",
        },
      },
    },
  ],
  [
    {
      descriptions: {
        attrs: {
          lang: "en",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "uk",
        },
      },
    },
    {
      descriptions: {
        attrs: {
          lang: "en-GB",
        },
      },
    },
  ],
];

Js Filter – This only works when I know the messaging

let objectToBeRemove = [{ error: {}, message: "Cannot read property 'attrs' of undefined" }];
filtData = filtData.filter((obj) => objectToBeRemove.some((objToRemove) => JSON.stringify(objToRemove) !== JSON.stringify(obj)));

Express Validator is ignored and API sends errors from Mongoose

I have a route that POSTs new products. In it I am handling express validator and in this case I validate that the category and the provider are not empty but it never throws and stops the check message and goes to the Mongoose error message. This is the code:


router.post('/', upload.array('pictures', 3),
    [
        jwtValidation,

        role('SUPER_ROLE','WAREHOUSE_ROLE'),

        check('category', 'La Categoría del producto es obligatoria').not().isEmpty(),
        check('category', 'No es un Id de Categoría Válido').isMongoId(),

        check('provider', 'El Proveedor del producto es obligatorio').not().isEmpty(),
        check('provider', 'No es un Id de Proveedor Válido').isMongoId(),
 
        check('barCode', 'El Código de producto es obligatorio').not().isEmpty(),
        check('barCode').custom( productBarCodeExists ),

    ], 
    validateOrDeleteProductImages, 
    newProduct
);

And when trying to create a new product I get this error from Mongoose:
error mongoose

And even if I pass some random string, it still indicates the error but the validation of express validator is never executed.

Thanks for your help.

Quill for blazor with @bind-Value=@

There are several ready made projects available, also couple of NuGet packages to download. I have found good option in NuGet library. However it is missing some customization in JavaScript interop. How I can take sources from NuGet package to use them independently in my project or as an option how to get it working without any NuGet?

So I have created

QuillEditor.razor:

@inherits InputTextArea
@inject IJSRuntime JSRuntime

<textarea value="@CurrentValue"></textarea>

QuillEditor.razor.cs:

using Microsoft.AspNetCore.Components;
using Microsoft.JSInterop;
using System;
using System.Threading.Tasks;

namespace Client.Shared.Components
{
  public partial class QuillEditor
  {        
    protected override async Task OnAfterRenderAsync(bool firstRender)
    {
      if (firstRender)
        await this.JSRuntime.InvokeVoidAsync("QuillInterop.init", DotNetObjectReference.Create(this));

      await base.OnAfterRenderAsync(firstRender);
    }

    [JSInvokable]
    public Task EditorDataChanged(string data)
    {
      this.CurrentValue = data;
      StateHasChanged();
      return Task.CompletedTask;
    }
  }
}

quill.js:

window.blazor = {};
window.blazor.quill = {
    initialize: function (id, value, dotnet) {

        var dataOptions = JSON.parse(document.getElementById(id).getAttribute("data-options"));
        var defaultOptions = {
            modules: {
                toolbar: [
                    [{ header: [1, 2, 3, 4, 5, 6, false] }],
                    ["bold", "italic", "underline", "strike"],
                    [{ 'list': "ordered" }, { 'list': "bullet" }, { 'indent': "-1" }, { 'indent': "+1" }],
                    ["link", "image", "blockquote"]
                ]
            },
            theme: "snow"
        };

        var options = Object.assign({}, defaultOptions, dataOptions);
        var quill = new Quill(`#${id}`, options);

        quill.on("text-change", function (delta) {
            dotnet.invokeMethodAsync("quill-onchange", quill.container.firstChild.innerHTML);
        });

        quill.container.firstChild.innerHTML = value;
    }
};

Above code is not working as I am not sure how to tie all together.

Basically I would like to understand how this has been done, but as original GitHub project seems to be deleted, I don’t understand how it has been done? Can somebody drop some light?
https://www.nuget.org/packages/BlazorQuill/

Unable to compile Typescript: property send does not exist on s3client

I’m using v3 of the AWS SDK for javascript in a typescript/nodejs environment, but when I run it with ts-node, it complains about being unable to find the send function on the s3client. My code:

const client = new S3Client({
  credentialDefaultProvider: this.getCredentialDefaultProvider
  region: "us-west-2",
});
const command = new ListObjectsCommand({
  Bucket: bucket,
  Prefix: prefix,
});
const result = await client.send(command);

The error I get when starting my server is this:

/server/node_modules/ts-node/src/index.ts:230
  return new TSError(diagnosticText, diagnosticCodes)

TSError: ⨯ Unable to compile TypeScript:
src/controllers/aws.controller.ts(56,37): error TS2339: Property 'send' does not exist on type 'S3Client'.

This is basically the same as the code samples in the official documentation. But I have installed the correct packages (and even cleared my node_modules folder and reinstalled it) and the code in node_modules looks correct. What am I doing wrong?

For context, this is a nodeJS script running in ts-node in a docker-compose container. Other code works fine, including a command to get a signedURL using the same client object.

Display and edit form Input in front end

I am new to wordpress and programming in general.
I need to create a solution for a client, with the following steps:

  1. A user enters some information to the site in a request form.
  2. An Administrator (logged in) from the company views the info in the site and updates the status
    of the request.
  3. The user enters a value and can access the info from his form so he can know the status of his
    request.
    So what I need is to create a form in a page and a way to see the input from that form in another page and that info needs to be editable. some fields need to be hidden depending in the user role.

I have been looking and I think I need to develop a plugin using PHP,I just don´t know where to start, can anyone point me in a direction that can help me?

Thanks!

Read file line by line and return all to a variable in NodeJS

I need to read a file line by line and store the result in a variable, is that possible?

const fs = require('fs');

const allFileContents = fs.readFileSync('test.log', 'utf-8');
allFileContents.split(/r?n/).forEach(line =>  {
  console.log(`Line from file: ${line}`);
  return line; *<-- Returns undefined because it goes through all the lines of the file, but could everything be stored in a single variable to return the result?*
});

File example:

1 Word
2 Word
3 Word

Failing to Access Outlet Context in React

Okay so I have scoured the internet for an example of how to do this but unfortunately I am not able to do so. Basically I have a componenet structure like this:

App.js

class App extends Componenent {
  render() {
     return (
        <Routes>
          <Route path='/signin' exact element={<SignIn />} />
          <Route path='/admin' exact element={<Admin />} >
             <Route path='home' exact element={<Home/>} />
             <Route path='settings' exact element={<Settings/>} />
        </Route >
     );
  }
}

export default App;

admin.jsx

import { useLocation, Outlet } from "react-router-dom";

const Admin = props => {
  const location = useLocation();

  return (
    <div>
       <p>Parent</p>
       <div>
          <Outlet context={'foo'} />
       </div>
    </div>
}

export default Admin;

settings.jsx

import React from "react";

const Settings = props => {
  const context = useOutletContext();
  console.log(context);

  return (
    <React.Fragment>
       <p>settings</p>
    </React.Fragment>
}

export default Settings;

However, each time I load the page, I get a an error that says exactly:

'useOutletContext' is not defined  no-undef

and the app crashes. However, when I look at my componenet tree with the chrome react debug panel, the context is there in the outlet, I just don’t know how to access it. Here are some screenshots so that we are on the same page:

Context is in the outlet
enter image description here

The same data is in the Context.Provider as “value” now
enter image description here

Nowhere to be seen in the Route.Provider
enter image description here

Nowhere to be seen in the Settings Componenet
enter image description here

Any and all help here would be appreciated, I am just not entirely sure of how to use useOuletContext(); even if I used followed the steps in the docs. Do I have to import it from somewhere? Does it have to be in the same file for it to work?

JavaScript Object -make key as value [duplicate]

API Response –

{ "00041335": { "productId": "8e786e6b", "itemId": "0b43df16" } },
{ "00032183": { "productId": "9e780e6d", "itemId": "0b48df17" } }

need this way using reduce or better way –

[
  { skuId: "00041335", "productId": "8e786e6b", "itemId": "0b43df16" },
  { skuId: "00032183", "productId": "9e780e6d", "itemId": "0b48df17" }
]