Using Mantine UI .tsx file within a javascript based react project

I currently am building a fitness website and am looking to use Mantine UI accordion component which is based off Typescript. I built my react project with javascript. Is there a way to create a .tsx file and call it into my app.js file?

Here’s the error I am currently receiving. Am I missing the export on the Accordian code?

Module not found: Error: Can't resolve './components/Faq' in '/Users/rodriguezmedia/Desktop/blended/src'


    import { Group, Avatar, Text, Accordion } from '@mantine/core';
import React from 'react';

const charactersList = [
  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-bender.png',
    label: 'Bender Bending Rodríguez',
    description: 'Fascinated with cooking, though has no sense of taste',
    content: "Bender Bending Rodríguez, (born September 4, 2996), designated Bending Unit 22, and commonly known as Bender, is a bending unit created by a division of MomCorp in Tijuana, Mexico, and his serial number is 2716057. His mugshot id number is 01473. He is Fry's best friend.",
  },

  {
    image: 'https://img.icons8.com/clouds/256/000000/futurama-mom.png',
    label: 'Carol Miller',
    description: 'One of the richest people on Earth',
    content: "Carol Miller (born January 30, 2880), better known as Mom, is the evil chief executive officer and shareholder of 99.7% of Momcorp, one of the largest industrial conglomerates in the universe and the source of most of Earth's robots. She is also one of the main antagonists of the Futurama series.",
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/homer-simpson.png',
    label: 'Homer Simpson',
    description: 'Overweight, lazy, and often ignorant',
    content: 'Homer Jay Simpson (born May 12) is the main protagonist and one of the five main characters of The Simpsons series(or show). He is the spouse of Marge Simpson and father of Bart, Lisa and Maggie Simpson.',
  },
  {
    image: 'https://img.icons8.com/clouds/256/000000/spongebob-squarepants.png',
    label: 'Spongebob Squarepants',
    description: 'Not just a sponge',
    content: 'SpongeBob is a childish and joyful sea sponge who lives in a pineapple with his pet snail Gary in the underwater city of Bikini Bottom. He works as a fry cook at the Krusty Krab, a job which he is exceptionally skilled at and enjoys thoroughly. ',
  },
]

interface AccordionLabelProps {
  label: string;
  image: string;
  description: string;
}

function AccordionLabel({ label, image, description }: AccordionLabelProps) {
  return (
    <Group noWrap>
      <Avatar src={image} radius="xl" size="lg" />
      <div>
        <Text>{label}</Text>
        <Text size="sm" color="dimmed" weight={400}>
          {description}
        </Text>
      </div>
    </Group>
  );
}

function Demo() {
  const items = charactersList.map((item) => (
    <Accordion.Item label={<AccordionLabel {...item} />} key={item.label}>
      <Text size="sm">{item.content}</Text>
    </Accordion.Item>
  ));

  return (
    <Accordion initialItem={-1} iconPosition="right">
      {items}
    </Accordion>
  );
}

Liquid Script based on Conditional JQuery

Let’s suppose we have a dropdown toggle:

<label for="num-of-records">Rows per Page: </label>
<select name="num-of-records" id="num-of-records">
  <option value="" selected>default</option>
  <option value="25">25</option>
  <option value="50">50</option>
</select>

And we also have a liquid code:

{% include 'page' key: 'table' %}

For key, I have provide some options table,table25, and table50 for each dropdown options value.

I am new to liquid, but I want to create a jquery which select the key value based on the dropdown.

<script>
$.(this).append("{% include 'page' key: 'table"+ $.(#num-of-records).val()+"' %}"
</script>

So let’s say I choose option 25, so it will (maybe reopen the page) append liquid script of:

{% include 'page' key: 'table25' %}

How would I fix this camera mouse glitch in ThreeJS

I’ve been working with ThreeJS for a couple of days now and i’ve come across a problem that i’ve seen happen in other online games. When I turn my camera using the PointerLockControls, it makes the camera go to a previous or random rotation. How would I fix this?

Here is the code that I am using for the camera:

import {PointerLockControls} from "three/examples/jsm/controls/PointerLockControls";
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
const controls = new PointerLockControls( camera, renderer.domElement );
document.addEventListener('click', () => {
    document.querySelector("#bg").requestPointerLock();
});

It looks like this: https://youtu.be/RjcVDSZSvfg

How do I fix this?

JQuery Datatables Ajax Datasource Error – Requested unknown parameter

I’m pretty stuck as to why I’m receiving this error from JQuery Datatables “DataTables warning: table id=myTable – Requested unknown parameter ‘0’ for row 0, column 0. For more information about this error, please see http://datatables.net/tn/4″. I’ve tried to review the website info but it didn’t make much sense to me. My only guess is that it has something to do with the way the data may be formatted. If so, I’m unsure how to resolve the issue.

This chunk of code is getting the API so I can view it in the console and then again for the datatable data.

      var apiKey = "0ca80ddc-63f6-476e-b548-e5fb0934fc4b";
      $.ajax({
          type: "GET",
          url: "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
          headers: { "api-key": apiKey },
          success: function(result){
            console.log(result)
            console.log(JSON.stringify(result));
          }
      });
      $(document).ready( function () {
        $('#myTable').dataTable({          
          "ajax": {
            "url": "http://brew-roster-svc.us-e2.cloudhub.io/api/teams",
            "type": "get",
            "dataSrc": "",
            "beforeSend": function (request) {
              request.setRequestHeader("api-key", apiKey);
            },
            "columns": [
              { "data": "logo" },
              { "data": "name" },
              { "data": "league" },
              { "data": "division" },
            ],
          }
        });
      });

Here are the results from my debugging Ajax results in the console.

(30) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]

This portion is a snippet of what I see when expanded:

0: {id: 133, nickname: 'Athletics', name: 'Oakland Athletics', location: 'Oakland', abbreviation: 'OAK', …}
1: {id: 134, nickname: 'Pirates', name: 'Pittsburgh Pirates', location: 'Pittsburgh', abbreviation: 'PIT', …}
[[Prototype]]: Array(0)

Is there a 10MB upload issue with PHP or Javascript?

At the moment I am trying to upload “large” files to a webhosting server.
For this I use an input field with multiple=’multiple’. Maximum file size is not set for this input field.
The PHP version is 7.4.
The maximum upload size is set to 256MB by the hoster.

The files are processed by js in a simple loop ( files[ x ] ).
The issue is that files larger than 10MB do not get any payload on upload. I generate formdata with file-chunks or full files appended which is only sent when files/chunks are below 10MB or when I let bigger files being sliced via Javascript to chunks under 10MB. The PHP $_FILES- array stays empty on 10MB+ files and the formdata is not available nor shown on upload in chrome/ff dev tools. The requests are sent via jquery $.ajax() after trying fetch and jquery $.POST(). All show the same behaviour. No errors are shown.

By the fact that I can upload 10MB+ files when slicing them to anything under 10MB via javascript slice() and any file below 10MB seems to show me that it is not a script- issue. Files under 10MB work, too when I set the chunk- size to something like 100MB or 200MB which is within the maximum upload size limitation.

Is there any known Apache/nginx server limitation that I might have missed?

Access to XMLHttpRequest at “SOME-URL” from origin ‘localhost’ has been blocked by CORS policy. Redirect is not allowed for a preflight request

I am coding a Vue.js application. I created an API using python and hosted it using Heroku. But whenever I try to fetch JSON from this API, there is an error. I tried it on another API (Google Dictionary API: ‘https://api.dictionaryapi.dev/api/v2/entries/en/hello’), and it works just fine.

Here is the code:

methods: {
    calculate() {
      // Use this API call:
      // http://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=<code>/
      const url = 'https://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=' + this.code;
      axios.get(url, {
        headers: {
          'Content-Type': 'application/json',
          'Accept': 'application/json',
          'Access-Control-Allow-Origin': 'http://localhost:8080/',
        }
      })
        .then(response => {
          console.log(response.data);
          this.complexity = response.data;
        })
        .catch(error => {
          console.log(error);
        });
    }
  }

This is the error that I get: Access to XMLHttpRequest at ‘https://gpt3-model.herokuapp.com/api/type=text-ada-001/prompt=hi,%20how%20are%20you?/’ from origin ‘http://localhost:8080’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: Redirect is not allowed for a preflight request.

Why is the property “dadType” being set to all the options avalable and staying with the last one, rather than the one selected?

It’s basicaly a text based adventure game i thought would be a fun first project.

Game.js

const textElement = document.getElementById('text')
const optionButtonsElement = document.getElementById('option-buttons')

let factions =["Grill Dad","Sports Dad","Car Dad","Vacation Dad","Drama Dad","The Craft Dad"]
let state = {
  dadType : '',
  items : ''
}
//variables
function startGame() {
  state = {}
  showTextNode(1)
}
//make a function to show the first prompt and reset "state"
function showTextNode(textNodeIndex) {
  const textNode = textNodes.find(textNode => textNode.id === textNodeIndex)
  textElement.innerText = textNode.text
  while (optionButtonsElement.firstChild) {
    optionButtonsElement.removeChild(optionButtonsElement.firstChild)
  }
//function to remove options with no text
  textNode.options.forEach(option => {
    if (showOption(option)) {
      const button = document.createElement('button')
      button.innerText = option.text
      button.classList.add('btn')
      button.addEventListener('click', () => selectOption(option))
      optionButtonsElement.appendChild(button)
    }
  })
}
//function to add options till you run out
function showOption(option) {
  return option.requiredState == null || option.requiredState(state)
}
//function to check for "state"
function selectOption(option) {
  const nextTextNodeId = option.nextText
  if (nextTextNodeId <= 0) {
    return startGame()
  }
  state = Object.assign(state, option.setState)
  showTextNode(nextTextNodeId)
}
//function to advance to the next prompt and assign "state"
/*function randNum() {
let rand = Math.floor(Math.random() * 5)
}
//random generator
function getDadType(state){
  return state.dadType
}
//get dad type (not working)
*/
const textNodes = [
  {
    id: 1,
    text: 'Insert adventure description here pick a faction of dad to play as.',
    options: [
      {
        text: factions[0],
        setState: state = {dadType: 'grill dad'} ,
        nextText: 2
      },
      {
        text: factions[1],
        setState: state = {dadType: 'sports dad'},
        nextText: 2
      },
      {
        text: factions[2],
        setState: state = {dadType: 'car dad'},
        nextText: 2
      },
      {
        text: factions[3],
        setState: state = {dadType: 'vacation dad'},
        nextText: 2
      },
      {
        text: factions[4],
        setState: state = {dadType: 'drama dad'},
        nextText: 2
      },
      {
        text: factions[5],
        setState: state = {dadType: 'craft dad'},
        nextText: 2
      },
      {
        text: 'Placeholder for Random',
        setState: {},
        nextText: 2
      },
      {
        text: 'Placeholder for Back',
        nextText: 2
      }
     ]
  },
  {
    id: 2,
    text: "First part of backstory "+state.dadType,
    options:[
    {
      text: 'some things you could say',
      nextText: 1
    }
startGame()

The property “dadType” is supposed to be set to whatever dadtype you selected in the first text node, but rather than setting it, and then ignoring the rest of the option buttons, it seems to run through all the options. I want it to just set the last ones property. It will still go to the correct next window, but the correct property is not set.

I want to directly call the result value by arithmetic operation on two state values

I want to display (salePrice + manualSettlementAmount), (salePrice -manualSettlementAmount), values ​​according to the operation of sale state ‘+’, ‘-‘. And these result values ​​are put in settlementAmount.

And the arithmetic operation values ​​are calculated in onBlurSettlementAmount.

  const [form, setForm] = useState({
    sign: "+",
    salePrice: "",
    manualSettlementAmount: "",
    settlementAmount: 0,
  })

  const onChangeSign = (event: React.ChangeEvent<HTMLSelectElement>) => {
    setForm({...form, sign: event.target.value}); 
  } 

  const onChangeSalePrice = (event: React.ChangeEvent<HTMLInputElement> | any) => {
  setForm({...form, salePrice: event.target.value});
  }

  const onChangeManualSettlementAmount = (event: React.ChangeEvent<HTMLInputElement> | any) => {
    setForm({...form, manualSettlementAmount: event.target.value });

  }

  const onBlurSettlementAmount = (event: React.ChangeEvent<HTMLInputElement> | any) => {

    if (form.sign == '+') {
      setForm({ ...form, settlementAmount: (Number(form.salePrice) + Number(form.manualSettlementAmount ))})
    } 
  
    if (form.sign == '-') {
      setForm({ ...form, settlementAmount: (Number(form.salePrice) - Number(form.manualSettlementAmount ))})
    }
    
  }

return (
 <>
       <select value={form.sign} onChange={onChangeSign}>
                  <option label="+" value={"+"}>+</option>
                  <option label="-" value={"-"}>-</option>
       </select>

      <input type="text" value={form.manualSettlementAmount} onChange={onChangeManualSettlementAmount} />
      
      <input type="text" value={form.salePrice} onChange={onChangeSalePrice} />      

      <input type="number" disabled={true} value={form.settlementAmount} onBlur={onBlurSettlementAmount} />
 </>
)

However, the value of settlementAmount in input continues to appear as an initial value of 0, and the arithmetic operation value is not displayed. I don’t know why.

After inputting both sign and salePrice, whenever I input the manualSettlementAmount value, I want the settlementAmount value to be displayed as well.. How should I handle it?

Is it not possible to do arithmetic operations in onBlur?

How i fit the entire text and image to fit in this card component

I have made a carousel in which there is a right and left slider. the text and image coming in the card component are not fit. actually there are surpassing the container i want to make them fit.

Text and photo in card component
in this component is it not coming in card instead only some item. i want them to assign in proper order and within the frame but not happening

INDEX

<!DOCTYPE html>
<html lang="en">
  <head>
    <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 rel="stylesheet" href="style.css" />

    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
      integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
      crossorigin="anonymous"
    />
  </head>

  <body>
    <div class="slide hi-slide">
      <div class="hi-prev"></div>
      <div class="hi-next"></div>

      <ul>
        <li>
          <div class="card" style="width: 18rem">
            <img src="1.jfif" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images (1).jfif" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images (1).png" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images.jfif" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images.png" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images.png" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images.png" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
        <li>
          <div class="card" style="width: 18rem">
            <img src="images.png" alt="Img 1" height="90px" />
            <div class="card-body">
              <h5 class="card-title">Card title</h5>
              <p class="card-text">
                Some quick example text to build on the card title and make up
                the bulk of the card's content.
              </p>
              <a href="#" class="btn btn-primary">Go somewhere</a>
            </div>
          </div>
        </li>
      </ul>
    </div>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script type="text/javascript" src="script.js"></script>
    <script>
      $(".slide").hiSlide();
    </script>
  </body>
</html>

STYLE

body {
  font-family: "Roboto Condensed", sans-serif;
  overflow-x: hidden;
  background-color: rgba(0, 0, 0, 0.9);
}

body {
  background-image: url(ur.jpg);
}

h1 {
  margin: 150px auto 30px auto;
  text-align: center;
  color: red;
}

.hi-slide {
  position: relative;
  width: 754px;
  height: 292px;
  margin: 115px auto 0;
}

.hi-slide .hi-next,
.hi-slide .hi-prev {
  position: absolute;
  top: 50%;
  width: 40px;
  height: 40px;
  margin-top: -20px;
  border-radius: 50px;

  line-height: 40px;
  text-align: center;
  cursor: pointer;
  background-color: #fff;
  color: black;
  transition: all 0.6s;
  font-size: 20px;
  font-weight: bold;
}

.hi-slide .hi-next:hover,
.hi-slide .hi-prev:hover {
  opacity: 1;
  background-color: #fff;
}

.hi-slide .hi-prev {
  left: -60px;
}

.hi-slide .hi-prev::before {
  content: "<";
}

.hi-slide .hi-next {
  right: -60px;
}

.hi-slide .hi-next::before {
  content: ">";
}

.hi-slide > ul {
  list-style: none;
  position: relative;
  width: 754px;
  height: 292px;
  margin: 0;
  padding: 0;
}

.hi-slide > ul > li {
  overflow: hidden;
  position: absolute;
  z-index: 0;
  left: 377px;
  top: 146px;
  width: 0;
  height: 0;
  margin: 0;
  padding: 0;
  border: 3px solid #fff;
  background-color: #333;
  cursor: pointer;
}

/* .hi-slide > ul > li > img {
  width: 100%;
  height: 100%;
  background-position: center;
} */

SCRIPT

(function ($) {
  var slide = function (ele, options) {
    var $ele = $(ele);

    var setting = {
      speed: 1000,

      interval: 10000,
    };

    $.extend(true, setting, options);

    var states = [
      {
        $zIndex: 1,
        width: 120,
        height: 150,
        top: 69,
        left: 134,
        $opacity: 0.2,
      },
      { $zIndex: 2, width: 130, height: 170, top: 59, left: 0, $opacity: 0.4 },
      {
        $zIndex: 3,
        width: 170,
        height: 218,
        top: 35,
        left: 110,
        $opacity: 0.7,
      },
      { $zIndex: 4, width: 224, height: 288, top: 0, left: 263, $opacity: 1 },
      {
        $zIndex: 3,
        width: 170,
        height: 218,
        top: 35,
        left: 470,
        $opacity: 0.7,
      },
      {
        $zIndex: 2,
        width: 130,
        height: 170,
        top: 59,
        left: 620,
        $opacity: 0.4,
      },
      {
        $zIndex: 1,
        width: 120,
        height: 150,
        top: 69,
        left: 500,
        $opacity: 0.2,
      },
    ];

    var $lis = $ele.find("li");
    var timer = null;

    $ele.find(".hi-next").on("click", function () {
      next();
    });
    $ele.find(".hi-prev").on("click", function () {
      states.push(states.shift());
      move();
    });
    $ele
      .on("mouseenter", function () {
        clearInterval(timer);
        timer = null;
      })
      .on("mouseleave", function () {
        autoPlay();
      });

    move();
    autoPlay();

    function move() {
      $lis.each(function (index, element) {
        var state = states[index];
        $(element)
          .css("zIndex", state.$zIndex)
          .finish()
          .animate(state, setting.speed)
          .find("img")
          .css("opacity", state.$opacity);
      });
    }

    function next() {
      states.unshift(states.pop());
      move();
    }

    function autoPlay() {
      timer = setInterval(next, setting.interval);
    }
  };

  $.fn.hiSlide = function (options) {
    $(this).each(function (index, ele) {
      slide(ele, options);
    });

    return this;
  };
})(jQuery);

Fibonacci sequence with recursive function works but I cant understand how

for anyone familiar with the Fibonacci sequence I wrote this function using a recursive algorithm that was on a bit of a whim. It is indeed working but I can not wrap my head around how. If anyone can explain this to me or point me to a resource I would be super appreciative

function fibonacciRecursive(n) {

    let startPoint = 0;
    let secondPoint = 1;
    let indexVal = 0;


    if (n === 0) {
        return startPoint;
    }

    if (n === 1) {
        return secondPoint;

    }

    indexVal = startPoint + secondPoint;

    startPoint = secondPoint;
    secondPoint = indexVal;

    return indexVal * fibonacciRecursive(n)

}

// fibonacci seq => 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144

My code works but I don’t think it is good. How to improve it?

Is there a way to beautify my code? It works but there repeated blocks and I am not sure that I’m using some functions in the right way.
I’m not new to javascript but I want to improve it and get rid of Bad Coding Habits.

Below is my code snippet that I’m using on the server to upload product images to cloud storage using multer and sharp.

const EasyYandexS3 = require('easy-yandex-s3')
const multer = require('multer')
const sharp = require('sharp')
const slug = require('slug')

const s3 = new EasyYandexS3({
  auth: {
    accessKeyId: process.env.KEY_ID,
    secretAccessKey: process.env.SECRET_KEY,
  },
  Bucket: process.env.BACKET, // Название бакета
  debug: false, // Дебаг в консоли
})

const storage = multer.memoryStorage()
const fileFilter = (req, file, cb) => {
  if (
    file.mimetype === 'image/jpeg' ||
    file.mimetype === 'image/jpg' ||
    file.mimetype === 'image/png'
  ) {
    cb(null, true)
  } else {
    cb(null, false)
  }
}

const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 1024 * 1024 * 5, // ограничение до 5 мб
  },
})

const uploadFields = upload.fields([
  { name: 'cover', maxCount: 1 },
  { name: 'media', maxCount: 4 },
])

const uploadImages = (req, res, next) => {
  uploadFields(req, res, (err) => {
    if (err instanceof multer.MulterError) {
      if (err.code === 'LIMIT_UNEXPECTED_FILE') {
        return res.send('Превышено количество файлов.')
      }
    } else if (err) {
      return res.send(err)
    }
    next()
  })
}
const resizeImages = async (req, res, next) => {
  // Функция загрузки фотографий в бакет
  async function transform(size, file, filename, type) {
    const folder = slug(req.body.title)
    const resizedImgFilename = `${filename}-${size}`
    const resizedImgBuffer = await sharp(file.buffer)
      .resize(size)
      .toFormat('jpeg')
      .jpeg({ quality: 90 })
      .toBuffer()
    const upload = await s3.Upload(
      {
        buffer: resizedImgBuffer,
        name: resizedImgFilename,
      },
      `/products/${folder}/`
    )
    if (size === 800) {
      type.push(upload.Location.slice(0, -4))
    }
  }

  // Проверяем какие файл загружены
  if (req.files.media === undefined && req.files.cover === undefined) {
    return next()
  } else if (req.files.media === undefined) {
    await Promise.all(
      req.files.cover.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c'
        const type = req.body.cover
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  } else if (req.files.cover === undefined) {
    await Promise.all(
      req.files.media.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm'
        const type = req.body.media
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  } else {
    await Promise.all(
      req.files.media.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'm'
        const type = req.body.media
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
    await Promise.all(
      req.files.cover.map(async (file) => {
        const filename = Date.now() + Math.round(Math.random() * 1e2) + 'c'
        const type = req.body.cover
        await transform(800, file, filename, type)
        await transform(400, file, filename, type)
        await transform(250, file, filename, type)
      })
    )
  }
  next()
}

module.exports = {
  uploadImages,
  resizeImages,
}

Do all error objects in Javascript have the same structure?

I’m implementing error outputting modal in React web app and therefore instead of just using .catch((e) => console.log(e) I’m planning to pass the error details into a separate component and display 3 parts of this error object: name, message, stack, in separate fields of this component.

I know that standard Error type object has all of those properties, however, I was wondering whether there are some exceptions and some error could be returned without all of these fields?

How to store JSON in variable from fetch API

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

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

}

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

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

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

Creating like button for multiple items

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

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

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

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

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

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

  `