Use a certain object instance in multiple modules without global variables

I have an object instance that’s used by several different modules in my code. The instance itself gets edited during different events, then the modules use it to redraw the page.

Right now, I keep passing it into the module functions when they’re called, but that means that I need to always have it in the scope of the script that’s calling the module. I can get around this by using global variables but I’d rather not pollute the namespace for other modules that don’t rely on it.

Is there a way that I can make this instance accessible in the specific modules that need it and still have it editable? Maybe using import?

Does AWS Javascript SDK v3 automatically read credentials from local config?

I’m looking at this page https://docs.aws.amazon.com/sdk-for-javascript… and it seems to imply that the SDK will look at ~/.aws/credentials and take the [default] profile if there is no AWS_PROFILE environment var.

I’m running a NextJS app on my local machine trying to list S3 buckets, getting Error: Credential is missing.

I would really love not to have to specify the creds in env vars as I’ll be deploying the app to ECS later where it will use an IAM Role for access.

Here’s my code:

import { ListBucketsCommand } from '@aws-sdk/client-s3';
import React, { useEffect } from 'react';
import { s3Client } from '../lib/s3Client';

const S3Buckets = () => {
    useEffect(() => {
        async function getS3Buckets() {
            const input = {};
            const command = new ListBucketsCommand(input);
            const res = await s3Client.send(command);
            console.log(res);
        }
        getS3Buckets();
    }, []);

    return <div>{/* S3 Buckets eventually listed here */}</div>;
};

export default S3Buckets; 

with the s3Client helper as below:

import { S3Client } from '@aws-sdk/client-s3';

export const s3Client = new S3Client({ region: process.env.AWS_REGION });

how to make a multiple user editor profile

I have been having trouble with creating an HTML site with a user-changeable profile picture. For example, being able to upload and change your profile picture on employee profiles. I’ve tried many methods, so I really can’t put any code down for revision, but here’s what I thought should work:

`

<div class="profile-pic">
    <img src="img/ananthu-1.jpg" id="output"  style="width:120px; height:120px;"> 
        <label for="file" class="-label">
            <span>Change Photo</span>
        </label>
        <input type="file" accept="image/*" id="file" onchange="loadFile(event)">
                                
 </div>
  <hr>
      <div class="profile-pic">
        <img src="img/ananthu-1.jpg" id="output"  style="width:120px; height:120px;"> 
            <label for="file" class="-label">
               <span>Change Photo</span>
            </label>
            <input type="file" accept="image/*" id="file" onchange="loadFile(event)">
                                
      </div>

`

    .profile-pic {
  color: transparent;
  transition: all 0.3s ease;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}
.profile-pic input {
  display: none;
}
.profile-pic img {
  position: relative;
  object-fit: cover;
  box-shadow: 0px 1px 4px rgba(0, 0, 0, 0.12) !important;
  z-index: 0;
}
.profile-pic .-label {
  cursor: pointer;
  position: absolute;
  bottom: 0;
}
.profile-pic:hover span {
  background-color: rgba(0, 0, 0, 0.8);
  color: #fafafa;
  transition: background-color 0.2s ease-in-out;
  display: inline-block;
  padding: 0.2em;
  height: 2em;
  text-align: center;
}

    
**JS:**
var loadFile = function (event){
        var image = document.getElementById("output");
        image.src = URL.createObjectURL(event.target.files[0]);
        }

Can’t run JS file using node js

I’m trying to run my first NodeJS program.
This is the JS file looks like

var http = require('http')

http.createServer(function(req,res) {
    res.write("Hello world")
    res.end()
}).listen(8080)

Tried running this file as node filename.js in the current folder and it doesn’t open the server, literally blank terminal after executing node filename.js.Can’t find an solution..

NaN result after mapping array with number values

I am trying to map a simple array that looks like this: [1,2,3,4,5], but the result is coming as
NaNNaNNaNNaN12345.

It looks like I am making an error with the mapping, but I don’t know what it could be.

  function getPagingRange(current, {min = 1, total = 20, length = 5} = {}) {
    if (length > total) length = total;

    let start = current - Math.floor(length / 2);
    start = Math.max(start, min);
    start = Math.min(start, min + total - length);
  
    return Array.from({length: length}, (el, i) => start + i);
  }

  const paginationRange = getPagingRange(1);
    {paginationRange.map(el => (
        <button onClick={() => setCurrentPage(el)} key={el} >
            {el}
        </button>
      ))}
The result: NaNNaNNaNNaN12345

Is it bad practice to use a uuid passed into the session cookie for the purpose of authorisation to make other queries to the database

I use a uuid v4 to generate custom userId that is then stored in the session cookie for facilitate authorisation and authentication. I also store this userId in the database to uniquely identify users. On some of my api’s i have the server return that userId as a means to identify users. For example, if i built a reddit clone and i have an end point that returns all the posts from a particular subreddit with each post having the userId of the author. Is this bad practice? I don’t want to use the auto generated primary key for each table to uniquely identify users, because since its sequential, it can be guessed.

Javascript Blob.slice() method & potential memory usage issue?

I’m writing a client-side upload script that pre-chunks the input data before sending.

I was just wondering if this could potentially lead to a huge memory spike, calling the slice method on the potentially very big File (e.g., slicing a 2GB file into 1000x2MB chunks) before starting the upload, as opposed to slicing it just before each chunk upload starts.

I figured the browser is not actually handling the data with the slice method, it’s just returning a new instance of Blob with a different start and end range, but I just want to be sure.

I know it’s easily testable but I’m not sure if I can trust a test result on Chrome would apply to all browsers.

reply from group chat (telegram bot – support) (NODE JS)

help please, I am writing a telegram bot for feedback, at the moment it works in a private chat (i.e. the user writes to the bot – I answer reply the bot via reply and the user receives SMS from the bot), but does not work in the group chat( in a group I can see the user’s messages, but I can’t reply to the user through reply). it is necessary that any user from the group can reply to the user’s message

 const bot = new Telegraf(token, {});

let replyText = {
    'helloAdmin': '...',
    'helloUser': '...',
    'replyWrong': '....'
};
let isAdmin = userId => {
    return userId === admin;
};
let forwardToAdmin = ctx => {
    if (isAdmin(ctx.message.from.id)) {
        ctx.reply(replyText.replyWrong);
    } else {
        ctx.forwardMessage(admin, ctx.from.id, ctx.message.id);
    }
};
bot.start(ctx => {
    ctx.reply(isAdmin(ctx.message.from.id)
        ? replyText.helloAdmin
        : replyText.helloUser);
});

bot.on('message', ctx => {
    if (ctx.message.reply_to_message && ctx.message.reply_to_message.forward_from && isAdmin(ctx.message.from.id)) {
        ctx.telegram.sendCopy(ctx.message.reply_to_message.forward_from.id, ctx.message);
    } else {
        forwardToAdmin(ctx);
    }
});
bot.launch();

loop objects in array | React

I’m getting a list from the backend. There are 5 objects in my incoming list. I want to loop through only those whose “status” is “6”. There is also a “continue” button. I will not show this button depending on the situation.

response

status 3 = invoice paid

status 6 = unpaid invoice

policyInstallmentDtoList: Array(5)
 0: {installmentNumber: 1, amount: 3032, currency: 'USD', status: '3', date: '09-06-2022'}
 1: {installmentNumber: 2, amount: 3032, currency: 'USD', status: '3', date: '09-07-2022'}
 2: {installmentNumber: 3, amount: 3032, currency: 'USD', status: '6', date: '09-08-2022'}
 3: {installmentNumber: 4, amount: 3032, currency: 'USD', status: '6', date: '09-09-2022'}
 4: {installmentNumber: 5, amount: 3032, currency: 'USD', status: '6', date: '09-10-2022'}

js

  const [hiddenControlButtonClass, setHiddenControlButtonClass] = useState('policypaymentinfo__button_container');

  useEffect(() => {
    if (paymentInfoData?.policyInstallmentDtoList?.map((payment) => payment.status)) {
      setHiddenControlButtonClass('hidden');
    } else {
      setHiddenControlButtonClass('policypaymentinfo__button_container');
    }
  }, [paymentInfoData]);

policyInfoData is the name of the incoming list.

html

<PaymentTable variant="edit" paymentList={paymentInfoData} value={value} collectionMethod={collectionMethod} />
<div className={hiddenControlButtonClass}>
  <AS.Button variant="outlined" onClick={handlePayment}>
    Contiune
  </AS.Button>
</div>

How to insert a sharepoint item when i have a lookup from a dropdownlist populated from javascript

i have a problem when trying to insert an new item in sharepoint programatically. The problem is in a dropdown list that i populate from another sharepoint list using rest api with javascipt. When i remove the javascript code the insertion works fine and when i add it back i have an error. Any idea how to resolve the problem?

    //Action de formation
        //GetItems
        function getListItemsByListName1(arg) {
            var listName = arg.listName;
            var selection = arg.select;
            var filter = arg.filter;
            var expansion = arg.expansion;
            var order = arg.order;
            if (selection) { selection = '?$select=' + selection; } else selection = '?$select=*';
            if (filter) { filter = '&$filter=' + filter; } else filter = '';
            if (expansion) { expansion = '&$expand=' + expansion; } else expansion = '';
            if (order) { order = '&$orderby=' + order; } else order = '';
            return $.ajax({
                url: "/_api/web/lists/getByTitle(%27" + listName + "%27)/items" + selection + filter + expansion + order + "&$top=100000",
                method: "GET",
                headers: { "Accept": "application/json; odata=verbose" },
            });
        }

        //Action de formation
        getListItemsByListName1(
            {
                listName: 'Formations ELSAN',
                select: 'CodeFormation,TitreDeLaFormation,ID',
                order: 'CodeFormation asc'
            }).done(function (data) {

                //Action de formation
                var af = document.getElementById('<%= AFDDL.ClientID %>');

                for (var index = 0; index < data.d.results.length; index++) {
                    var option = document.createElement("OPTION");
                    var element = data.d.results[index];
                    option.innerHTML = element.TitreDeLaFormation;
                    option.value = element.ID;
                    af.options.add(option);
                }
                return false;
            });

        //Etablissement
        getListItemsByListName1(
            {
                listName: 'Etablissements',
                select: 'Title,ID',
                order: 'Title'
            }).done(function (data) {

                //Etablissement
                var etablissement = document.getElementById('<%= EtablissementDDL.ClientID %>');

                for (var index = 0; index < data.d.results.length; index++) {
                    var option = document.createElement("OPTION");
                    var element = data.d.results[index];
                    option.innerHTML = element.Title;
                    option.value = element.ID;
                    etablissement.options.add(option);
                }
                return false;
            });

        //}

this is the button i use :

<!-- Ajouter  -->
    <asp:Button ID="Button1" runat="server" Text="Ajouter" OnClick="AjouterBT_Click" /> 

This is the C# code :

    protected void AjouterBT_Click(object sender, EventArgs e)
    {
            SPWeb spWeb = SPContext.Current.Web;
            SPList spList = spWeb.Lists["PDC"];

            SPListItem listItem = spList.Items.Add();

            //Code catalogue Université ELSAN
            //listItem["CodeCatalogueUniversiteELSAN"] = Request.Form[CodeCatalogUniELSANTB.UniqueID];
            //listItem["CodeCatalogueUniversiteELSAN"] = CodeCatalogUniELSANTB.Text;

            listItem["CodeCatalogueUniversiteELSAN"] = "CODE TEST";

            //Budgé impacté
            //listItem["BudgeImpacte"] = BudgeImpDDL.Text;

            listItem["BudgeImpacte"] = "0,6%";


            //Etablissement


            //var etablissement = spWeb.Lists["Etablissement"].GetItemById(idEtab); //Achats 183
            //listItem["Etablissement"] = new SPFieldLookupValue(etablissement.ID,etablissement.Title);

            listItem["Etablissement"] = new SPFieldLookupValue(183, "Achats");


            listItem["LF"] = "LfTB.Text";

            //Durée en heures par stagiaire
            //listItem["DHS"] = DhsTB.Text;

            listItem["DHS"] = 100;


            listItem.Update();
        

    }


}

}

This is the error i have :
Click to view screenshot

hide only the div clicked in react instead of all elements returning in map function

the json response is received form dummy user data API.
when I click on read more button all components returning in map get expanded/hidden .
I want it to show/hide the text of specific div that is clicked

    import React, { useState } from 'react'
    const UserBlock = (props) => {
      //styles strings
      const infoTitle = `font-bold`
      //Hooks
      const [laodMoreClicked, loadMoreStatus] = useState(false)
      const [viewMoreClass, setViewMoreClass] = useState("hidden")
//functions
      const viewMore = () => {
        laodMoreClicked === true ? loadMoreStatus(false) : loadMoreStatus(true);
        laodMoreClicked === true ? setViewMoreClass("hidden") : setViewMoreClass("")
      }
const singleUser = props.userArray.map((user, index) => {
        return (
          <div key={index} className="
        bg-gray-900 text-white m-2 p-10 w-full rounded-2xl shadow-lg
     m-8 md:w-1/4 lg:w-1/6">
            <p className={`${infoTitle} text-xl`}>  username:  {user.name}</p>
            <div className={viewMoreClass}>
              <p className={infoTitle}>  email:  {user.email}  </p>
              <p className={infoTitle}>  website:  {user.website}  </p>
              <p className={infoTitle}>  phone: {user.phone}  </p>
              <p className={infoTitle}>  address: </p>
              <p className={infoTitle}>  suite: {user.address.suite}  </p>
              <p className={infoTitle}>  street:  {user.address.street}  </p>
              <p className={infoTitle}>  city:  {user.address.city}  </p>
              <p className={infoTitle}>  zipcode: {user.address.zipcode}  </p>
            </div>
            <div>
              <button onClick={viewMore}>
                View {laodMoreClicked === true ? `${index} Less` : "More"}
              </button>
            </div>
          </div>
        )
      })
      return (
        <div className='flex flex-wrap w-full justify-center '>
          {singleUser}
        </div>
      )
    }
    export default UserBlock

Fill Datatable with Variable dont work. But if i put the exact same value to a php site and request it with ajax. It works…. Why?

This is in the variable “test”:

{"data":[{"HistChar_ID":"4","Vorname":"Garnier","Nachname":"de
 Naplouse"},{"HistChar_ID":"2","Vorname":"Robert","Nachname":"de
 Sable"},{"HistChar_ID":"7","Vorname":"Ibn","Nachname":"Dschubair"},{"HistChar_ID":"6","Vorname":"Baha
 ad-Din","Nachname":"ibn
 Schaddad"},{"HistChar_ID":"1","Vorname":"Richard","Nachname":"Lu00f6wenherz"},{"HistChar_ID":"5","Vorname":"Wilhelm","Nachname":"von
 Montferrat"}]}

HTML:

<table id="example" class="display" style="width:100%">
    <thead class="thead1">
        <tr>
            <th class="th1">HistChar_ID</th>
            <th class="th2">Vorname</th>
            <th class="th3">Nachname</th>
        </tr>
    </thead>
    <tfoot class="tfoot1">
        <tr>
            <th class="th1">HistChar_ID</th>
            <th class="th2">Vorname</th>
            <th class="th3">Nachname</th>
        </tr>
    </tfoot>
</table>

An the following Code Wont fill the Datatable.

$('#example').DataTable({       
    data: test, 
    columns: [
        { data: 'HistChar_ID'  },
        { data: 'Vorname' },
        { data: 'Nachname' },
    ]

it throws an Error like this:

DataTables warning: table id=example – Requested unknown parameter
‘HistChar_ID’ for row 0, column 0. For more information about this
error, please see http://datatables.net/tn/4

I tried so much. But if i take whats inside of “test” and put it into a php and use ajax it works just fine with this.

    $('#example').DataTable({
        ajax: 'RESOURCES/PHP/Searchfield.php',
        columns: [
            { data: 'HistChar_ID' },
            { data: 'Vorname' },
            { data: 'Nachname' },

        ]

Can someone explain me why? Is it impossible to fill the Datatable with a variable?? I just dont get it…

How I can reset variable value when function end?

I have such function and global variable (as array):

const arraysList = []

export const changeColorCategories = (array, draggedColumnId) => {
    const isColor = arraysList.length ? arraysList[0][0]?.color : [];

    if (typeof isColor === 'string') {
        firstLevelColor = isColor;
    }

    return array.map((item, index, categories) => {
        item.color = draggedColumnId !== 3 ? '#010172' : '#000000';
        arraysList.push(categories);
        
        if (firstLevelColor && !draggedColumnId) {
            item.color = firstLevelColor;
        }

        if (item?.children?.length) {
            changeColorCategories(item.children);
        }
        
        return item;
    })
} 

Every call of this function push some data to array. In this function I use recursion. So how i can clear this array only when this function will end it’s work.