How do I render folders within a folder in one component in React(Next.js)?

I’m not good at English so please be understanding.

First, please check my code.


const DriveFile = ({folderPk}) => {

    const [rootFolder, setRootFolder] = useState([])

    const viewFolder = async () => {
        const url = `/api/store/drive/view-folder?folderId=${folderPk}`
        await get(url)
        .then((res) => {
            setRootFolder(res.directChildrenFolders);
        })
        .catch((error) => {
            console.log(error)
        })
    };

    useEffect(() => {
        viewFolder()
    }, [folderPk]);

    const [folderName, setFolderName] = useState('');

    const folderNameChange = (e) => {
        setFolderName(e.target.value)
    }

    const createFolder = () => {
        const url = '/api/store/drive/create-folder';
        const data = {
            folderName: folderName,
            parentPK: folderPk
        }
        if (folderName.length == 0) {
            alert('please write the folder name');
            return;
        }
        post(url, data)
        .then((res) => {
            console.log('파일 생성', res)
            setFolderName('');
        })
        .catch((error) => {
            console.log(error)
        })
    };

    return (
        <div className={styles.fileDiv}>

            <input value={folderName} onChange={folderNameChange}/><button onClick={createFolder}>ADD FOLDER</button>
            {
                rootFolder?.map((root) => (
                    <div>{root.FOLDER_NAME}</div>
                ))
            }
        </div>
    )
}

export default DriveFile

Here. this is my component.

The props, {folderPk}, is just a number that I selected from the top root folder then I use GET request using folderPk to render the direct child folders.

FYI, this is the UI.

enter image description here

So, when I click ‘FOLDER 1’, I get the specific FOLDER_PK. Then, I use it in different component to render subfolders like that.

However, my question is how can I get into a folder within a folder in a component.

For example, I’m trying to go into another folder when I click ‘FOLDER 4, UNDER FOLDER 1’ folder. I’m wondering can it be possible.

Is it possible in one component? or should I use different method?

Your answer will be really appreciated!!!!! 🙂

JS: Sequence files not being read in the correct order

I have the following script which reads in all images from a directory and

async function createGif(algorithm) {
  return new Promise(async resolve1 => {
    const files = await promisify(readdir)(imagesFolder)

    // Bunch of other things
    // Happening here

    // draw an image for each file and add frame to encoder
    for (const file of files) {
      await new Promise(resolve3 => {
        const image = new Image()
        console.log(`reading ${file}`)
        image.onload = () => {
          ctx.drawImage(image, 0, 0)
          encoder.addFrame(ctx)
          resolve3()
        }
        image.src = path.join(imagesFolder, file)
      })
    }
  })
}

The images are of the pattern: image1,image2,image3,…image30.

However, the files are being read in this order when I check the console:

reading screenshot1.png
reading screenshot10.png
reading screenshot11.png
reading screenshot12.png
reading screenshot13.png
reading screenshot14.png
reading screenshot15.png
reading screenshot16.png
reading screenshot17.png
reading screenshot18.png
reading screenshot19.png
reading screenshot2.png
reading screenshot20.png

Why is it skipping from screenshot1 to screenshot10? It should be reading the files in the correct order in which they are in the directory. Like this:

reading screenshot1.png
reading screenshot2.png
reading screenshot3.png
...
reading screenshot10.png

How can I fix this?

Json file getting passed as javascript object in express nodejs?

I am using the follwing line to import a json file in my code. However, instead of a config file, the jsonConfig variable is getting a javascript object and I can directly access, jsonConfig.children. Why is this happening? And how can I just import a json file instead of the object.

const jsonConfig = require('../../config/myconfig.json');

How to create Next and Previous button to switch through Bootstrap tabs

I have created a form that goes across three different tabs named ‘contact-tab’ ‘questions-tab’ ‘delivery-tab’. I am trying to add Next and Previous buttons to flick through these tabs. Currently you can click on the tab name to get to that page, But I want to replace this with the next and previous buttons. But i cant seem to crack it.

I have tried various pieces of code from all over. And for some reason none of it works. I have replaced my code with there’s completely and still doesn’t work.

Im not good with JS myself so i couldnt make up a function myself. But i have tried different things from posts. Below is an example of what i have done most recently. I have chopped it all down so it is a minimal reproducible code snippet.

<script>
        $(document).ready(function(){
        $('a[data-bs-toggle="tab"]').on("shown.bs.tab", function(e){
            console.log(e.target); // newly activated tab
            console.log(e.relatedTarget); // previous active tab
            });
        });
    </script>
    <script>
        function bootstrapTabControl(){
            var i, items = $('.nav-link'), pane = $('.tab-pane');
            // next
            $('.nexttab').on('click', function(){
                for(i = 0; i < items.length; i++){
                    if($(items[i]).hasClass('active') == true){
                        break;
                    }
                }
                if(i < items.length - 1){
                    // for tab
                    $(items[i]).removeClass('active');
                    $(items[i+1]).addClass('active');
                    // for pane
                    $(pane[i]).removeClass('show active');
                    $(pane[i+1]).addClass('show active');
                }

        });
        // Prev
        $('.prevtab').on('click', function(){
            for(i = 0; i < items.length; i++){
                if($(items[i]).hasClass('active') == true){
                    break;
                }
            }
            if(i != 0){
                // for tab
                $(items[i]).removeClass('active');
                $(items[i-1]).addClass('active');
                // for pane
                $(pane[i]).removeClass('show active');
                $(pane[i-1]).addClass('show active');
            }
        });
}
bootstrapTabControl();
    </script>
    <head>
        <script src="https://kit.fontawesome.com/69362e78c5.js" crossorigin="anonymous"></script>
        <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
        <?php require_once __DIR__ . '/header.phtml'; ?>
    </head>
    <body>
        <div class="container">
                <ul class="nav nav-tabs">   <!--Using a list to create the tabs -->
                    <li class="nav-item">
                        <a href="#contact-tab" class="nav-link active" data-bs-toggle="tab">Contact Details</a>
                    </li>
                    <li class="nav-item">
                        <a href="#questions-tab" class="nav-link" data-bs-toggle="tab">Questions</a>
                    </li>
                    <li class="nav-item">
                        <a href="#delivery-tab" class="nav-link" data-bs-toggle="tab">Delivery Info</a>
                    </li>
                </ul>
<!-------------------------------------------------------------------------------------------------------------------------------------------------  -->
                <form class="row g-3" action="<?= $data['action'] ?>" method="post">
                    <div class="tab-content">       <!-- This involves the tav content -->
                        <div class="tab-pane fade show active" id="contact-tab">

                            <div class="row">       <!-- start row here -->
                                <h1>Contact & Site Details</h1>
                                <div class="col-md-7">
                                    <label for="site_name" class="form-label">Site Name*</label>
                                    <input type="text"
                                        class="form-control"
                                        id="site_name"
                                        name="site_name"
                                        value="<?= $data['record']['site_name'] ?? '' ?>"
                                        placeholder="Enter Site Name"
                                        required><br>
                                </div>
                            </div>
                            <button class="nexttab">Next</button>
                        </div>

                        <div class="tab-pane fade" id="questions-tab">
                            <div class="row">
                                <div class="col-12">
                                    <h6 for="current_machine">1. What is your Current Machine?</h6>
                                        <input type="text"
                                            class="form-control"
                                            id="current_machine"
                                            name="current_machine"
                                            value="<?= $data['record']['current_machine'] ?? '' ?>"
                                            placeholder="Leave blank if none"><br>
                                </div>
                            </div>
                        </div>

                        <div class="tab-pane fade" id="delivery-tab">
                            <div class="row">
                                <div class="col-12">
                                    <h6 for="q7">9. What floor is the Machine(s) going to be located on?</h6>
                                        <input type="text"
                                            class="form-control"
                                            id="q7"
                                            name="q7"
                                            value="<?= $data['record']['q7'] ?? '' ?>"
                                            placeholder="Please enter what floor your machine will be located on"> <br><br>
                                </div>
                        </div>
                        
                </div>
            </form>
        </div>
    </body>

How to duplicate elements?

I want that whenever someone clicks on plus-icon a new form field should be created same as this one new form field should be below to this one. all the buttons should be duplicated as well.

const container = document.querySelector(".container");
    
    
    // Creating a SPAN element and appending it to div
    container.addEventListener("click", (e) => {
      const tgt = e.target.closest(".icons");
      if (tgt) {
        if (tgt.classList.contains("swapped")) return; // stop
        if (tgt.classList.contains("check-icon")) {
          tgt.classList.add("swapped");
          let texts = document.querySelectorAll(".text");
          let items = document.querySelectorAll(".items");
          texts.forEach((text, i) => {
            let span = document.createElement("span");
            let val = document.createTextNode(text.value ? text.value : "");
            span.appendChild(val);
            span.classList.add("text2");
            items[i].appendChild(span);
            if (text.value) text.value = ""; // setting the input value to empty once clicked onto the check button
            text.parentNode.replaceChild(span, text);
    
            let btns = document.querySelectorAll(".mainicon"); // changing icon from check to edit
            if (tgt.classList.contains("check-icon")) {
              Array.from(btns).forEach((ele) => {
                ele.classList.toggle("hidden");
                            if (ele.classList.contains("edit-icon")) {
                ele.classList.remove("swapped");
                }
    
              });
    
            }
    
          });
    
        }
        if (tgt.classList.contains("edit-icon")) {
    
          let texts = document.querySelectorAll(".text2");
          let items = document.querySelectorAll(".items");
          texts.forEach((text, i) => {
            let input = document.createElement("input");
            input.value = text.textContent;
            input.classList.add("text");
            items[i].appendChild(input);
            text.parentNode.replaceChild(input, text);
    
            let btns = document.querySelectorAll(".mainicon"); // changing icon from check to edit
            Array.from(btns).forEach((ele) => {
              ele.classList.toggle("hidden");
        if (ele.classList.contains("check-icon")) {
                ele.classList.remove("swapped");
                }
    
            });
    
          });
    
        }
    
    
      }
    
    });





<!DOCTYPE html>
    <html lang="en">
      <head>
        <title>Document</title>
        <link rel="stylesheet" href="style.css" />
        <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css"
          integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA=="
          crossorigin="anonymous"
          referrerpolicy="no-referrer"
        />
      </head>
      <body style="background-color: #007bff">
        <div class="mainContainer">
          <h1 class="heading">Details Collector</h1>
          <div class="container">
            <div class="items">
              <label class="label" for="Name">Name :</label> &nbsp;&nbsp;&nbsp;
              <input class="text" type="text"/>
            </div>
            <div class="items">
              <label class="label" for="State">State :</label> &nbsp;&nbsp;&nbsp;
              <input class="text" type="text"/>
            </div>
            <div class="items">
              <label class="label" for="Country">Country :</label> &nbsp;&nbsp;&nbsp;
              <input class="text" type="text"/>
            </div>
    
            <div class="check-icon icons mainicon">
              <i class="fa fa-check " aria-hidden="true"></i>
            </div>
          
          <div class="edit-icon icons hidden mainicon" >
            <i class="far fa-edit " aria-hidden="true"></i> 
          </div>
    
    
            <div class="plus-icon icons ">
              <i class="fa fa-plus" aria-hidden="true"></i>
            </div> <br>
        </div>
          </div>
        </div>
    
        <script src="app.js"></script>
      </body>
    </html>

JS Fiddle

ESP32 Web Server Chart Does Not Change

I have been trying web server using Arduino İDE and ESP32. I want my web server graph to plot my list data (double vRealCustom[samples]). I draw a graph but the graph didn’t change. It always plots to the first variable in the list(-12.51). I see temAxis is change from the serial monitor. Where do you think I went wrong?

It is my .ino code:

#include <Wire.h>
#include <ESPAsyncWebServer.h>
#include <SPIFFS.h>
const uint16_t samples = 20;
double vRealCustom[samples] = {
  -12.51,  -5.06,  -5.49,  -8.55,  -7.37,  -8.08,  -5.73, -10.59,
  -11.81,  -3.49,  -2.79, -15.42, -16.83,  -2.12, -17.06, -17.34,
  -2.35, -16.83, -16.55, -15.3 
  };

const char* ssid = "********";
const char* password = "*******";

AsyncWebServer server(80);
String readAxis(uint16_t j) 
{
      float t = vRealCustom[j]; 
      Serial.print("t ->"); Serial.println(t);
      return String(t);
  }
 
void setup(void) 
{
#ifndef ESP8266
  while (!Serial); // for Leonardo/Micro/Zero
#endif
  Serial.begin(115200);
    // Initialize SPIFFS
  if(!SPIFFS.begin()){
    Serial.println("An Error has occurred while mounting SPIFFS");
    return;
  }

  // Connect to Wi-Fi
  WiFi.begin(ssid, password);
  while (WiFi.status() != WL_CONNECTED) {
    delay(1000);
    Serial.println("Connecting to WiFi..");
  }
    
  // Print ESP32 Local IP Address
  Serial.println(WiFi.localIP());

  server.begin();
  // Route for root / web page
  server.on("/", HTTP_GET, [](AsyncWebServerRequest *request){
    request->send(SPIFFS, "/index.html");
  });
   for(uint16_t j = 0; j<20;j++ ){     
    delay(400);
    String tempAxis = readAxis(j); 
    Serial.println(tempAxis);
    server.on("/zAxis", HTTP_GET, [=](AsyncWebServerRequest *request){
      request->send_P(200, "text/plain", tempAxis.c_str());
      delay(400);
      
  });}
}
 
void loop(void) 
{
 
}

It is my javascript code:

<!DOCTYPE HTML><html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://code.highcharts.com/highcharts.js"></script>
  <style>
    body {
      min-width: 310px;
        max-width: 800px;
        height: 400px;
      margin: 0 auto;
    }
    h2 {
      font-family: Arial;
      font-size: 2.5rem;
      text-align: center;
    }
  </style>
</head>
<body>
  <h2>EXAMPLE</h2>
  <div id="chart-zAxis" class="container"></div>
</body>
<script>
var chartZAxis = new Highcharts.Chart({
  chart:{ renderTo:'chart-zAxis' },
  title: { text: 'Z Axis' },
  series: [{
    showInLegend: false,
    data: []
  }],
  plotOptions: {
    line: { animation: false,
      marker: {
            enabled: false,
      dataLabels: { enabled: true }
    }
    },
    series: { color: '#27F416' }
  },
  xAxis: {
    type: 'datetime',
    dateTimeLabelFormats: { second: '%H:%M:%S' }
  },
  yAxis: {
    title: { text: 'Z Axis' }
  },
  credits: { enabled: false }
});
setInterval(function ( ) {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      var x = new Date().getTime(),
          y = parseFloat(this.responseText);
      if(chartZAxis.series[0].data.length > 40) {
        chartZAxis.series[0].addPoint([x, y], true, true, true);
      } else {
        chartZAxis.series[0].addPoint([x, y], true, false, true);
      }
    }
  };
  xhttp.open("GET", "/zAxis", true);
  xhttp.send();
}, 800 ) ;
</script>
</html>

Add data to chart properly

Hey folks I have a task to show user data on the chart (I’m using react-native slide charts) but it becomes a little bit tricky.
So what I’m trying to achieve is next:
I’m making a request and get the next data from the server:

{
  "trend": [92, 93, 94, 94, 93, 93, 94, 95, 95, 95, 95, 94, 96, 95, 96],
  "history": [1087, 112, 117, 190, 153, 163, 138, 166, 191, 191, 187, 163, 187, 177, 109, 107, 196, 175, 113, 192, 113, 112, 169, 109, 109, 157, 126, 170, 137, 146, 132, 114],
}

And I know that trend is data for the last 15 minutes with an interval of 1 min, and the history is data for the last 8 hours with an interval of 15 mins.

I need to map this data and show it on the chart. I’m trying to do the next:

const initialDateTime = dayjs();

const mappedTrend = data.trend.reverse().map((el, i) => ({
      x: i === 0 ? initialDateTime.valueOf() : initialDateTime.add(i * 1, 'minutes').valueOf(),
      y: el,
}));

const mappedHistory = data.history.reverse().map((el, i) => ({
      x: i === 0 ? initialDateTime.valueOf() : initialDateTime.add(i * 15, 'minutes').valueOf(),
      y: el,
}));

in output I have 2 arrays like {x: timestamp, y: value};

Then I’m adding it to the state and the chart looks at this data:

setState({data: [...mappedHistory, ...mapTrend]})

seems like it is ok till here, but now, for example, I need to load more data, after for example 5 minutes I can make another request and will get almost the same data but with different numbers, and I need now, to prolong the chart data with a new one, but how to do it? How to add data properly?

I prepared a snack here
Problems are, the chart is looking quirky and when new data comes it also shows strange. And the thing is, on chart data should be in range on 24h that’s why I use xRange on the chart.
So any ideas on how to solve this or fix it?

How to access root folder using module-resolver

I would like to access my package json on my react

on my babel, I have this config

  [
    'module-resolver',
    {
      root: ['.'],
      extensions: ['.js', '.json', '.png'],
      alias: {
        '@@': './',
        '@': './src'
      },
      
    },
  ]

But I’m having an error while importing the package

import { version } from '@@/package.json'

Cannot find module ‘@@/package.json’

Thanks!

Regex to accept comma and new line as optional for a input value

My input can accept comma-separated integer values with new line for each value as optional

Example:
option 1:

123,
456,
345

or option 2

123,234,456

or option 3

123,
234,
456,789 

both should be valid.

I have tried validating with regex '/^d+(,nd+)*$/,', this work for option1 in above example but fails for second and third.

help me to change this regex to fit in all the option.

How to filter through cards based on the value using onChange when selected in a dropdown

This is how I filter to get the string of objects from an array of objects displayImages which I got the the value of dropdown

  const locationNameDropdown = () => {
    return displayImages.map((data, key) => (
      <option key={key} value={data.locationName}>
        {data.locationName}
      </option>
    ));
  };

Here is my {onChange}

 const onChange = (e) => {
    if (e.target.value === "All") {
      setDisplayImages(null);
    } else {
      setDisplayImages([e.target.value]);
    }
  };

This is my card display

 const images = displayImages.map((data, key) => {
    return (
      <div key={key}>
        <div className="card bg-light mb-3" value={data.locationName}>
          <div className="card-header">
            <center>
              <h5>{data.locationName}</h5>
            </center>
          </div>
          <div className="card-body">
            <div className="mrtgDiv">
              <img src={data.filePath}  />
            </div>
          </div>
        </div>
      </div>
    );
  });

and this is the return

  return (
    <div>
      <div>
        <select className="form-select" onChange={onChange}>
          <option value="All" defaultValue>
            All
          </option>
          {locationNameDropdown()}
        </select>
      </div>
      <br />
      <br />

      <center>
        <h5>test</h5>
      </center>
      <div>{images}</div>
    </div>
  );

when I select the first item in the dropdown, I only get a blank card that has no value and when I select the “All” value I receive null I don’t know what to put in the IF ELSE

I want to display the images in a card that I select

HTML auto update select box

So I am writing code for people management webpage. All the result are generated by SQL, now I use Jquery to get result from Java Spring. The problem is I can save it into a JS list and make the update as a function, but I don’t know how I can update my select box.

For example, I got a JS list like this {“tom”,”jerry”}, what I want to have on HTML is enter image description here

and I run the function update() [when clicked a button called “update”]

the list become {“tom”,”jerry”,”spike”}

what I want to have now is enter image description here

so what should I do to achieve this on HTML using tag? Is their any specific data structure to achieve this?

the resource can be used to build this are

a list {"tom","jerry"}
and a function update()

how to make a payment gateway for cart with multiple items in react

I am using razorpay api as a payment gateway for my shopping website and I am stuck at creating multiple orders

it works perfectly fine when I order single product but when I try to checkout from cart where there are multiple product added, I get stuck about what to do for amount and description field because it sends array of product while its send single product when its ordered directly.

app.post("/payment", async (req, res) => {
  try {
    const { product } = req.body;
    console.log("product");
    const amount = product.price * 100;
    const currency = "INR";
    const receipt = product.id;
    const notes = { desc: product.desc };

    instance.orders.create({ amount, currency, receipt, notes }),
      (err, order) => {
        if (error) {
          return res.status(500).json({ err });
        }
        return res.status(200).json({ order });
      };
  } catch (err) {
    console.log(err);
  }
  res.json(res);
});

when I order directly

{
 b_name: "siyaram",
 id: 9,
 p_color: "white",
 p_img: {type: 'Buffer', data: Array(5771)},
 p_name: "kurta",
 p_price: 1000,
 p_size: "s m l"
}

when I order from cart

[
 {
  b_name: "raymond,
  id: 9,
  p_color: "yellow",
  p_img: {type: 'Buffer', data: Array(5771)},
  p_name: "kurta",
  p_price: 1000,
  p_size: "s m l"
 },
 {
  b_name: "peter England",
  id: 9,
  p_color: "red",
  p_img: {type: 'Buffer', data: Array(5771)},
  p_name: "kurta",
  p_price: 1300,
  p_size: "s m l"
 }
]

this throws an error cause here I have multiple product.

In ios, when getUserMedia is called again, the existing stream is killed

Problems with iPad using Safari with video chat app. We want to present the user’s video feed and provide the ability to select their own webcam device in a pop-up window. However, to show the selected webcam device, the video of the selected webcam is displayed in a pop-up window, but the original camera feed turns black and the audio is cut off. This seems to happen when calling navigator.mediaDevices.getUserMedia().

my code to get the device

const constraints = {
        speaker: {deviceId: audioOutputSelect.value ? {exact: audioOutputSelect.value} : undefined},
        audio: {deviceId: audioInputSelect.value ? {exact: audioInputSelect.value} : undefined},
        video: {deviceId: videoSelect.value ? {exact: videoSelect.value} : undefined}
    };
navigator.mediaDevices.getUserMedia(constraints).then((stream) => {
    ...
})

The biggest problem is that the audio of the existing video disappears.

How to make drag drop stay at dropped place after page refresh

Can someone please help me!

I am working on assignment with drag & drop and localstorage.
This is my first time wring a code involving localstorage. I’m creating
someting like kanban board.

The problem I am having right now is, I have no idea how am i going
to write code for getItem and make my card stay at the position where i drop
it after page refresh. I already write for setItem part and I think it works.
I can see the position change in the localstorage everytime I change it’s place.
Here is what i’ve tried so far

const todos = document.querySelectorAll(".todo");
const all_status = document.querySelectorAll(".box")


todos.forEach((todo) => {
  todo.addEventListener("dragstart", dragStart);
  todo.addEventListener("dragend", dragEnd);
});

function dragStart() {
  draggableTodo = this;
  setTimeout(() => {
    this.style.display = "none";

  }, 0);
  console.log("dragStart");
}

function dragEnd() {
  draggableTodo = null;
  setTimeout(() => {
    this.style.display = "block";

  }, 0);
  console.log("dragEnd");
}

all_status.forEach((box) => {
  box.addEventListener("dragover", dragOver);
  box.addEventListener("dragenter", dragEnter);
  box.addEventListener("draleave", dragLeave);
  box.addEventListener("drop", dragDrop);
});

function dragOver(e) {
  e.preventDefault();
  //console.log("dragOver");
}

function dragEnter() {
  console.log("dragEnter");
}

function dragLeave() {
  console.log("dragLeave");
}

function dragDrop() {
  this.appendChild(draggableTodo);
  var left = this.offsetLeft;
  var top = this.offsetTop;
  localStorage.setItem("left", left);
  localStorage.setItem("top", top);
  console.log("localStorage");
}

jsfiddle