How to download file directly in node response in react?

How do I download the document I receive in return in react?

Here is the my node.js app. fetchContracts is a function which getting data from mongodb then ganere a excel file by using json2xls npm package.

Its returns as like this:

    const xls = json2xls(contracts);
    return xls;

If tying to write file fs.writeFileSync(path.join(__dirname, filename), xls, 'binary'); generating successfully xlsx file in the server.

But I need to send the file to the server without writing file. For this, I made some experiments that you can see below.

export const EXPORT_EXCEL: SessionedAsyncControllerType = async (req: SessionedRequest, res: Response) => {

    const fileName = 'hello_world.xlsx'
    const fileType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    const xls = await fetchContracts({}, "fileName.xlsx")
    const fileData = xls;
    res.writeHead(200, {
        'Content-Disposition': `attachment; filename="${fileName}"`,
        'Content-Type': fileType,
    })
    const download = Buffer.from(fileData, 'base64')
    res.end(download)
}

I getting response like this.

response preview

But i don’t know how can i download the response file in react?

In react side:

return api.get(`api/excel`).then((response: any) => {
        console.log(response);
    })

I just log into console. How can i download directly file which coming node response in react.js?

Display object by its property value

I am still learning Javascript, and I have data and trying to to display by its category. I’m confused which method to use to achieved that. Here is my object

const data = [
  {
     category: "sports",
     items: "shoes",
     price: 599,
  },
  {
     category: "electronics",
     items: "phones",
     price: 898,
  },
  {
     category: "sports",
     items: "shirt",
     price: 788,
  },
  {
     category: "sports",
     items: "ball",
     price: 455,
  },
  {
     category: "electronics",
     items: "laptop",
     price: 999,
  },
  {
     category: "beauty",
     items: "lipstick",
     price: 888,
  },
];

The result that I want is more or less like the code snippet below. And thank for your help. I hope you guys understand, because my English is not good enough

div{
  display: flex
}

section{
  border: 1px solid red
}
<section>
  <h1>electronics</h1>
  <div>
    <p>phones</p>
    <p>898</p>
  </div>
  <div>
    <p>laptop</p>
    <p>999</p>
  </div>
</section>

<section>
  <h1>sports</h1>
  <div>
    <p>shoes</p>
    <p>599</p>
  </div>
  <div>
    <p>shirt</p>
    <p>788</p>
  </div>
  <div>
    <p>ball</p>
    <p>455</p>
  </div>
</section>

<section>
  <h1>beauty</h1>
  <div>
    <p>lipstick</p>
    <p>888</p>
  </div>
</section>

How can I change Xaxis tooltip style in Apexchart?

I make a line chart in React and try to look like the style of Figma. I need a change of the style of Xaxis toolbar.

This is my chart toolbar.

enter image description here

This is Figma chart toolbar.

enter image description here

My xaxis chart code

  xaxis: {
      categories: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
      labels: {
        show: true,
        style: {
          colors: "#D2D2D2",
        },
      },
      crosshairs: {
        width: 1,
        stroke: {
          color: "#1F51C1",
          dashArray: 0,
        },
      },
      axisTicks: {
        show: false,
      },
      tooltip: {},
    },

Organizing array of objects using specific object’s field value

I am having an array of objects which is structured like below

const data = [
{
depth:0,
id:1,
name:”data 1″
},
{
depth:0,
id:2,
name:”data 2″
},
{
depth:0,
id:3,
name:”data 3″
},
{
depth:1,
id:11,
name:”data 11″,
parentid:1,
},
{
depth:1,
id:12,
name:”data 12″,
parentid:1,
},
{
depth:1,
id:21,
name:”data 21″,
parentid:2,
},
{
depth:1,
id:31,
name:”data 31″,
parentid:3,
},
{
depth:2,
id:111,
name:”data 111″,
parentid:11,
},
{
depth:2,
id:112,
name:”data 112″,
parentid:11,
},
{
depth:2,
id:113,
name:”data 113″,
parentid:11,
},
{
depth:2,
id:121,
name:”data 121″,
parentid:12,
},
{
depth:2,
id:122,
name:”data 122″,
parentid:12,
},
{
depth:2,
id:211,
name:”data 211″,
parentid:21,
},
{
depth:3,
id:2111,
name:”data 2111″,
parentid:211,
},
{
depth:3,
id:2112,
name:”data 2112″,
parentid:211,
}]

I want the output like below

const output= [
    {
        depth:0,
        id:1,
        name:"data 1",
        childs:[
            {
                depth:1,
                id:11,
                name:"data 11",
                parentid:1,
                childs:[
                    {
                        depth:2,
                        id:111,
                        name:"data 111",
                        parentid:11,
                    },
                    {
                        depth:2,
                        id:112,
                        name:"data 112",
                        parentid:11,
                    },
                    {
                        depth:2,
                        id:113,
                        name:"data 113",
                        parentid:11,
                    },
                ]
            },
            {
                depth:1,
                id:12,
                name:"data 12",
                parentid:1,
                childs:[
                    {
                        depth:2,
                        id:121,
                        name:"data 121",
                        parentid:12,
                    },
                    {
                        depth:2,
                        id:122,
                        name:"data 122",
                        parentid:12,
                    },
                ]
            },
        ]
    },
    {
        depth:0,
        id:2,
        name:"data 2",
        childs:[
            {
                depth:1,
                id:21,
                name:"data 21",
                parentid:2,
                childs:[
                    {
                        depth:2,
                        id:211,
                        name:"data 211",
                        parentid:21,
                        childs:[
                            {
                                depth:3,
                                id:2111,
                                name:"data 2111",
                                parentid:211,
                            },
                            {
                                depth:3,
                                id:2112,
                                name:"data 2112",
                                parentid:211,
                            },
                        ]
                    }
                ]
            }
        ]
    },
    {
        depth:0,
        id:3,
        name:"data 3",
        childs:[
            {
                depth:1,
                id:31,
                name:"data 31",
                parentid:3,
            },
        ]
    },
]
  1. Key factor to achieve this output is depth,id,parentid
  2. Each childs array of objects’s parentid should be match their parent id.
    I had tried some map,filter,for loop methods but it’s not working as I expected. How can i achieve this output in Javascript?

Store Image files in an array based on index in React js fails. Image always gets added to single array item only

I’m trying to create an image upload window where users can upload product images based for different product variations.

The intended output looks like:

output

I’ve to store the image file and url linked to the variationId and variationOptionId that the rendered component belongs to.

However, no matter which “Add Image” button i click, images get added only to the first component (blue, in the above example).

The imageVariations state looks like:

variationId: '',
variationName: '',
variationOptionId: '',
variationOptionName: '',
images: [
    {
       file: null,
       url: '',
    }
],

Code of Parent Component:

import React, { useEffect, useState } from 'react';
import ItemContainer from '../../common/ItemContainer';
import ProductImageUpload from '../imageStockPrice/ProductImageUpload';

const Tab3ProductImages = ({ product, loading, setLoading }) => {
  
  const [imageVariations, setImageVariations] = useState([]);

  // loop over product.productVariations and get the variation
  // where variation.variesImage = true

  useEffect(() => {
    let tempVar = []; // has variationID, variationOptionID, and images array
    product &&
      product.productVariations.forEach((item) => {
        if (item.variation.variesImage) {
          tempVar.push({
            variationId: item.variationId,
            variationName: item.variation.name,
            variationOptionId: item.variationOptionId,
            variationOptionName: item.variationOption.name,
            images: [],
          });
        }
      });
    setImageVariations(tempVar);
  }, [product]);

  // console.log('imageVariations', imageVariations);

  const imageUploadHandler = () => {};
  const imageDefaultHandler = () => {};
  const imageDeleteHandler = () => {};

  return (
    <div className="py-4">
      <div className="space-y-4">
        {imageVariations &&
          imageVariations.map((imageVar, index) => (
            <div key={index}>
              <ItemContainer
                title={`${imageVar.variationName}: ${imageVar.variationOptionName}`}
              >

                <ProductImageUpload
                  loading={loading}
                  index={index}
                  imageVar={imageVar}
                  setImageVariations={setImageVariations}
                  imageUploadHandler={imageUploadHandler}
                />
              </ItemContainer>
            </div>
          ))}
      </div>
    </div>
  );
};

export default Tab3ProductImages;

Code of the Child component – ProductImageUpload:

import React from 'react';
import { RiImageAddFill } from 'react-icons/ri';
import { MdOutlineCancel } from 'react-icons/md';
import LoadingButton from '../../formComponents/LoadingButton';

const ProductImageUpload = ({
  loading,
  index,
  imageVar,
  setImageVariations,
  imageUploadHandler,
}) => {

  // Handling Images
  const handleImageChange = (e) => {
    const tempArr = [];
    [...e.target.files].forEach((file) => {
      tempArr.push({
        file: file,
        url: URL.createObjectURL(file),
      });
    });

    setImageVariations((prevState) => {
      const newState = [...prevState];
      newState[index].images = [...newState[index].images, ...tempArr];
      return newState;
    });
  };

  const removeImageFromList = (e) => {
    setImageVariations((prevState) => {
      const newState = [...prevState];
      newState[index].images = newState[index].images.filter((item) => {
        return item.url !== e.target.src;
      });

      return newState;
    });
  };

  return (
    <div className="space-y-4 grid grid-cols-1 md:grid-cols-2 gap-4">
      <div className="my-auto">
        <form onSubmit={imageUploadHandler}>
          <div className="flex gap-4">
            <label
              htmlFor="categoryImages"
              className="block w-full py-1 px-2 rounded cursor-pointer border 
               border-violet-700 bg-violet-50 hover:bg-violet-100 text-violet-700"
            >
              <span className="flex items-center gap-2">
                <RiImageAddFill />
                <span className="text-sm">Click to Add Images</span>
                <span className="font-barlow text-sm">(max 10 images)</span>
              </span>
              <input
                type="file"
                id="categoryImages"
                accept="image/*"
                multiple
                onChange={handleImageChange}
                className="sr-only"
              />
            </label>
            {loading ? (
              <LoadingButton />
            ) : (
              <button className="text-sm py-1 px-4 rounded cursor-pointer border 
                border-blue-700 bg-blue-50 hover:bg-blue-100 text-blue-700">
                Upload
              </button>
            )}
          </div>
        </form>
      </div>
      {/* upload progress bar */}
      <div className="flex items-center">
        <div className="bg-gray-200 w-full h-4 rounded-full overflow-hidden">
          <div
            className="h-4 bg-violet-500 text-xs font-medium text-center p-0.5 
                        leading-none rounded-full transition-all duration-75"
            style={{ width: `${progress}%` }}
          >
            <span
              className={`ml-2 ${
                progress === 0 ? 'text-gray-600' : 'text-blue-100'
              }`}
            >
              {progress}%
            </span>
          </div>
        </div>
      </div>
      {/* upload progress bar ends */}
      {/* image preview section */}
      <div>
        <ul className="flex flex-wrap gap-2">
          {imageVar &&
            imageVar.images.length > 0 &&
            imageVar.images.map((item, index) => (
              <li key={index} className="relative">
                <img
                  src={item.url}
                  alt="preview"
                  className="w-20 h-20 object-cover rounded shadow-lg border 
                            hover:scale-110 transition duration-200"
                />
                <button
                  onClick={removeImageFromList}
                  className="absolute -top-2 -right-2"
                >
                  <MdOutlineCancel className="text-red-400 bg-white" />
                </button>
              </li>
            ))}
        </ul>
      </div>
      {/* image preview section ends */}
    </div>
  );
};

export default ProductImageUpload;

why my lambda is not able to download file?

I am trying to download a file and store in /tmp of lambda, in log i can only see first hey, why i am not able to see any catch error or any other logs.

In local it works pretty fine.

const https = require('https');
const fs = require('fs');

// URL of the image
const url ='https://someurl';


exports.handler = async (event) => {
    console.log('hey')
  try {
       
  https.get(url, (res) => {
  console.log('hihi')    
  const path = '/tmp/' + 'testObject.obj';
  
  const writeStream = fs.createWriteStream(path);

console.log('hi')
  res.pipe(writeStream);
console.log('hi2')

  writeStream.on('finish', () => {
    writeStream.close();
    console.log('Download Completed!');
    console.log('ji')
  });
  
  console.log('hi5')
});
       
   }catch(error){
       
       console.log(error)
       
   }
   
 
};

How to assign usestate array values to Button onclick event in react js

I get api response from api and i stored it into usestate variables.

API response:

0:
Camera_Number: "Camera_1"
Company_Name: "Fraction Analytics Limited"
Floor Number: "Ground_Floor"
Group_Name: "Group_1"
Video_Name: "http://localhost:4000/video/0"
[[Prototype]]: Object

After that assign response to table headers using below code

 { headerName: "Camera", field: "Camera_Number" },
    { headerName: "Videos", field: "Video_Name" },
    {
      headerName: "Actions",
      field: "Video_Name",
      cellRendererFramework: (params) => (
        <div>
          <Button
            variant="contained"
            size="medium"
            color="primary"
            onClick={() => actionButton(params)}
          >
            Play
          </Button>

After that i stored api response in usestate

  const [response, setResponse] = useState([]);

Pass this usestate variable to popup video player

<DialogContent>
  {response.map(({ Video_Name }) => (
    <iframe width="420" height="315" title="videos" src={Video_Name} />
  ))}
</DialogContent>;

mapping usestate variable to video name and pass it to source for popup player but it play multiple video when i click play button

enter image description here

Instead of open multiple video i wanna one video play at a time how to resolve that using react js

if you want more code details

CLICK HERE

Can we merge object with same id in an array using javascript? [duplicate]

What I am going to do is to get target value from source_value.

    var source_value = [
    {
        "id": 111,
        "qty": 2,
        "price": 50
    },
    {
        "id": 222,
        "qty": 5,
        "price": 70
    },
    {
        "id": 111,
        "qty": 8,
        "price": 50
    },
];


var target_value = [
    {
        "id": 111,
        "qty": 10,
        "price": 50
    },
    {
        "id": 222,
        "qty": 5,
        "price": 70
    },
]

So in the source_value, there were 2 objects with same id value, and they were merged into one object and qty was added (2+8=10).
How can we do this in javascript?

How to add css attribute to a newly created element in JavaScript?

I am trying to add my element to the unordered list. But during the creation of the element I also want to link this to an external css file which has the css property.

My HTML file: index.html

<html>
<head>
    <link rel="stylesheet" href="index.css">
</head>
<body>
    <h1 id="header">Last King</h1>
    <h2>Buy Groceries</h2>
    <ul>
        <li id="one" class="hot"><em>fresh</em>figs</li>
        <li id="two" class="hot">pine nuts</li>
        <li id="three" class="hot">honey</li>
        <li id="four">balsamic sugar</li>

    </ul>
    <script src="index.js">

    </script>
</body>
</html>

My CSS File: index.css

.myclass {
    color: brown;
    text-emphasis-color:blue;
}

My JS File: index.js

let a = document.getElementsByTagName('ul')[0];

let myelement = document.createElement('li');

// tried this first 
myelement.style.border = '2px solid red';

myelement.style.backgroundColor = 'rgb(255, 125, 115)';

let mytext = document.createTextNode('Green Onions');


// second method I tried to link with the external CSS file which I actually want

myelement.setAttribute("class","myclass")


// third method I tried to link with the external CSS file which I actually want

let myattrib = document.createAttribute('class');
myattrib.value = "myclass"
myelement.setAttributeNode(myattrib)


a.appendChild(mytext)

None of these methods works in adding a new element with a CSS property, although with the first method I am able to just add the text node Green Onions.

I am learning JS for the first time.

Can someone provide me with information on what I am doing wrong?

I have referred following solutions.
Add CSS attributes to element with JavaScript

Testing components position (offsetLeft, offsetWidth) whose value is set in an event listener (keydown) callback

I am trying to test whether a component – say dynamicallyPositionedElement – has the correct position or not.

The position of the dynamicallyPositionedElement is set in the callback of an event listener (keydown in my case), which is triggered on onkeydown event registered on an element – say eventEmanantingElement.

So, basically to set the position of the dynamicallyPositionedElement, we get
the position of the eventEmanantingElement first and set the position of dynamicallyPositionedElement to the value of the position of eventEmanantingElement .

So, in the callback of onkeydown event we do,

setDynamicallyPositionedElement({
  left: e.currentTarget.offsetLeft, // currentTarget is the eventEmanatingElement
  width: e?.currentTarget.offsetWidth,
});

How can we test such a functionality? I am using React Testing Library.

disabling next button without radio button checked working only for 1st element in jquery

in my html website i have few questions where each questions have radio buttons as answers, i want the user to proceed to next question only when he selects any radio button of the question, i did the following code:

$('div.question').hide().first().show();


$('a.display').on('click', function(e) {

  e.preventDefault();


  var that = $('div.question:visible'),

    t = $(this).text();


  if (t == 'next' && that.next('div.question').length > 0) {
    if ($('input[type=radio]:checked').length > 0) {
      $('div.question').hide();


      that.next('div.question').show()
    } else {
      alert("Please Select an Option !");
    }
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<div class="question bg-white p-3 border-bottom">
  <div class="d-flex flex-row  question-title">
    <h3 class="text-danger">1. </h3>
    <h5 class="mt-1 ml-2">I try to be with people.</h5>
  </div>

  <div class="ans ml-2">
    <div class="form-check">
      <input class="form-check-input" name="q1" value="1" type="radio">
      <input class="form-check-input" name="q1" type="radio" value="2">
      <input class="form-check-input" name="q1" type="radio" value="3">
      <input class="form-check-input" name="q1" type="radio" value="4">
    </div>
  </div>
</div>


<div class="question bg-white p-3 border-bottom">
  <div class="d-flex flex-row  question-title">
    <h3 class="text-danger">1. </h3>
    <h5 class="mt-1 ml-2">I am sincere with people.</h5>
  </div>

  <div class="ans ml-2">
    <div class="form-check">
      <input class="form-check-input" name="q2" value="1" type="radio">
      <input class="form-check-input" name="q2" type="radio" value="2">
      <input class="form-check-input" name="q2" type="radio" value="3">
      <input class="form-check-input" name="q2" type="radio" value="4">
    </div>
  </div>
</div>

<a id="display" class="btn btn-info btn-sm display si">next</a>

here this works only for 1st question, after the 1st question, user is able to click next button without checking radio button, can anyone please tell me how to fix this, thanks in advance

Why does passing a large dictionary from python to julia flatten contained multidimensional lists? [closed]

Okay so…I’m in the process of creating a python client for a coding game I play. This game is originally created in javascript and employs a json object of game data found at https://adventure.land/data.js. Within this data, each map has a list of doors, and each door within this list is a list of attributes. For example:

"doors":[[-965,-176,24,30,"woffice",0,1],[536,1665,64,32,"tunnel",0,2],[168,-149,32,40,"bank",0,3],[160,1370,24,32,"cave",0,4],[232,384,24,30,"arena",0,6],[-472,131,24,30,"tavern",0,8],[616,610,32,40,"mansion",0,10],[1936,-23,24,24,"level1",1,11],[169,-404,24,40,"hut",0,14],[1600,-547,60,40,"halloween",4,15],[312,-335,32,32,"mtunnel",0,16],[967,-584,32,32,"mtunnel",1,17],[1472,-434,32,32,"mtunnel",2,18]]

However, when sent from python to julia, it suddenly becomes:

"doors":[-965,-176,24,30,"woffice",0,1,536,1665,64,32,"tunnel",0,2,168,-149,32,40,"bank",0,3,160,1370,24,32,"cave",0,4,232,384,24,30,"arena",0,6,-472,131,24,30,"tavern",0,8,616,610,32,40,"mansion",0,10,1936,-23,24,24,"level1",1,11,169,-404,24,40,"hut",0,14,1600,-547,60,40,"halloween",4,15,312,-335,32,32,"mtunnel",0,16,967,-584,32,32,"mtunnel",1,17,1472,-434,32,32,"mtunnel",2,18]

Is there some way to prevent this from happening? If not, is there a possible workaround? Because my for door in doors code in python won’t exactly have the same effect when given a direct translation to julia considering the random list flattening.