React Event Handling For Each Icon

How can I make handleclick operation unique for each icon? For example when click to plus icon, color of all changes to green. But I want only plus icon to change into green.

const [isActive, setIsActive] = useState(false);

  const handleClick = () => {
    setIsActive((current) => !current);
  };

return (

 <div className="list-icons">
                <FaPlus
                  className="plus-icon"
                  style={{
                    color: isActive ? "green" : "",
                  }}
                  onClick={handleClick}
                />
                <FaCheck
                  className="check-icon"
                  style={{
                    color: isActive ? "green" : "",
                  }}
                  onClick={handleClick}
                />
                <FaHeart
                  className="heart-icon"
                  style={{
                    color: isActive ? "green" : "",
                  }}
                  onClick={handleClick}
                />
              </div>
)

To pass a value from js(HTML) to Django backend

I have done a project on building a QR Code scanner using Javascript , the value of qr was returned in a js variable. Now i cannot pass the value to django backend for futher operations
My JS code

    <h4>SCAN RESULT</h4>
    <div id="result">Result Here</div>
function onScanSuccess(qrCodeMessage) {
    document.getElementById('result').innerHTML = '<span class="result">'+qrCodeMessage+'</span>';
}

I tried using Buttons instead of div so that clicking the button passes the button value to backend

<button type="submit" id="result" name="xyz">QR VALUE</button>

and in views.py

def qrscanner(request):
    obj=request.POST.get("xyz")
    print(obj)
    return render(request,"qr_scanner.html")

and this didn’t succeed either, is there any way i could pass the qr value to django views

Having trouble receiving data from api

I am new to working with REACT and I am having trouble receiving data from my api. I am using postman to help me build this project, so I am hoping I used it correctly. The app will show up with my table and pagination but not the information from my selected api. I am thinking I need to have my api as an array but how would I go about making my api into an array to properly show my data? here is my code:

import axios from "axios";
import _ from "lodash"; //lookup lodash
import Table from "react-bootstrap/Table";

const pageSize = 10;
const Posts = () => {
  const [_posts, set_posts] = useState();
  const [paginatedPosts, setPaginatedPosts] = useState();
  const [currentPage, setCurrentPage] = useState(1);

  useEffect(() => {
    axios.get("https://swapi.dev/api/people/").then((res) => {
      console.log(res.data);
      set_posts(res.data);
      setPaginatedPosts(_(res.data).slice(0).take(pageSize).value());
    });
  }, []);

  const pageCount = _posts ? Math.ceil(_posts.length / pageSize) : 0;
  if (pageCount === 1) return null;
  const pages = _.range(1, pageCount + 1);

  function pagination(pageNo) {
    setCurrentPage(pageNo);
    const startIndex = (pageNo - 1) * pageSize;
    const paginatedPosts = _(_posts).slice(startIndex).take(pageSize).value();
    setPaginatedPosts(paginatedPosts);
  }

  return (
    <div>
      {!paginatedPosts ? (
        "No data found"
      ) : (
        <Table striped bordered hover className="project--table">
          <thead>
            <tr>
              <th>Name</th>
              <th>Birth Year</th>
              <th>Height</th>
              <th>Mass</th>
              <th>Species</th>
              <th>Home World</th>
            </tr>
          </thead>
          <tbody>
            {paginatedPosts.map((_post, index) => (
              <tr key={index}>
                <td>{_post.name}</td>
                <td>{_post.birth_year}</td>
                <td>{_post.height}</td>
                <td>{_post.mass}</td>
                <td>{_post.species}</td>
                <td>{_post.home_world}</td>
              </tr>
            ))}
          </tbody>
        </Table>
      )}
      <nav className="d-flex justify-content-center">
        <ul className="pagination">
          {pages.map((page) => (
            <li
              className={
                page === currentPage ? "page-item active" : "page-item"
              }
            >
              <p className="page-link" onClick={() => pagination(page)}>
                {page}
              </p>
            </li>
          ))}
        </ul>
      </nav>
    </div>
  );
};

export default Posts;


The api I am using is the starwarsapi

Display javascript nested objects to html

Here is what the data looks like:

{
    "1111": {
        [{
            id: "1111",
            name: "name",
            randomvalue: "1",
        },
        {
            id: "1111",
            name: "name2",
            randomvalue: "2",
        }]
    },
    "0101": {
        [{
            id: "0101",
            name: "name3",
            randomvalue: "3"
        },
        {
            id: "0101",
            name: "name4",
            randomvalue: "1"
        }]
    },
    "0001": {
        [{
            id: "0001",
            name: "name5",
            randomvalue: "4"
        }]
    }
}

the randomvalue always changes when there is new data but the ids and names stay constant.
I want the data to be displayed on html exactly as it is here but when the random values update, the html must also be updated. I am not using any frameworks just nodejs.

For clarity:
for each object a new html <div> element will be created.
each <div> will have three <p> values.
the result will initially look like this:

<div class="container">
    <p class="id">1111</p>
    <p class="name">name</p>
    <p class="randomval">1</p>
</div>
<div class="container">
    <p class="id">1111</p>
    <p class="name">name2</p>
    <p class="randomval">2</p>
</div>
<div class="container">
    <p class="id">0101</p>
    <p class="name">name3</p>
    <p class="randomval">3</p>
</div>
<div class="container">
    <p class="id">0101</p>
    <p class="name">name4</p>
    <p class="randomval">1</p>
</div>
<div class="container">
    <p class="id">0001</p>
    <p class="name">name5</p>
    <p class="randomval">4</p>
</div>

if there is a randomvalue change in every object it will be:

<div class="container">
    <p class="id">1111</p>
    <p class="name">name</p>
    <p class="randomval"> <new_random_value> </p>
</div>
<div class="container">
    <p class="id">1111</p>
    <p class="name">name2</p>
    <p class="randomval"> <new_random_value> </p>
</div>
<div class="container">
    <p class="id">0101</p>
    <p class="name">name3</p>
    <p class="randomval"> <new_random_value> </p>
</div>
<div class="container">
    <p class="id">0101</p>
    <p class="name">name4</p>
    <p class="randomval"> <new_random_value> </p>
</div>
<div class="container">
    <p class="id">0001</p>
    <p class="name">name5</p>
    <p class="randomval"> <new_random_value> </p>
</div>

Formik with react-day-picker

I would like to create a form with a date picker. So i choose React DayPicker v8 now i would like to implement this picker in my current formik form.

I created a date picker component:

import React from "react";
import { Form, Popover, OverlayTrigger } from "react-bootstrap";
import { DayPicker, useInput } from "react-day-picker";
import "react-day-picker/dist/style.css";

const DatePicker = (props) => {
  const { inputProps, dayPickerProps } = useInput({
    format: "dd.MM.yyyy",
    required: true,
  });

  const handleChange = (value) => {
    props.onChange(props.name, value);
  };

  const popover = (
    <Popover id="popover-basic" className="mw-100">
      <Popover.Body>
        <DayPicker showWeekNumber weekStartsOn={1} {...dayPickerProps} />
      </Popover.Body>
    </Popover>
  );

  return (
    <>
      <OverlayTrigger
        rootClose
        trigger="click"
        placement="bottom-start"
        overlay={popover}
      >
        <Form.Control
          {...inputProps}
          onChange={handleChange}
          value={props.value}
          name={props.name}
          id={props.name}
        />
      </OverlayTrigger>
    </>
  );
};

export default DatePicker;

DatePicker.js

<Col>
  <Form.Group className="mb-3">
    <Form.Label htmlFor="startdate">Start Date</Form.Label>
    <DatePicker
      name="startdate"
      value={formikProps.values.startdate}
      onChange={formikProps.setFieldValue}
    />
  </Form.Group>
</Col>

Home.js

My problem is in my browser DevTools the value from datepicker changed correctly <input name="startdate" id="startdate" class="form-control" value="23.06.2022"> but in my formikProps.values.startdate I only get the old initialValue.

Is this the correct way? In a react-select field this code works completely fine.

Accessing Index From Within Then()

I am using OBS Websockets to connect to multiple OBS instances. As a result, I have a foreach() loop to loop over each instance, and call a connect function. This should connect to OBS and populate a dropdown list for each instance, showing available scenes.

My problem is I need to know which sheet I am on (index is part of the for loop, but because the function is async by the time it completes, the index has moved on:

for(sheetIndex = 0; sheetIndex  < 8; sheetIndex++)
{
    connect(sheetIndex);
}

function connect(sheetIndex)
{
    const obs = new OBSWebSocket();
        
    obs.connect({ address: address })
    .then(() => {
        console.log(`${name} connected on ${address}`);
          
        // get a list of the scenes
        await obs.send("GetSceneList").then((data) => {

        console.log("New sheet index: " + sheetIndex);

        data.scenes.forEach((scene) => {

              var sceneListSelect = document.getElementById("SceneListSheet" + sheetIndex);
              var opt = document.createElement("option");
              opt.innerHTML = scene.name;
              sceneListSelect.appendChild(opt);
        }
    });
}

The value of sheetIndex is unpredictable within the “then”, as the for loop has moved on to the next iteration before the call to GetSceneList completes. How can I pass in the value of sheetIndex in to the “then” function so its value is frozen at the time of calling?

How to remove empty objects from object by comparing with another object

I want to remove all empty objects from another object by comparing it with another. Example of this would be:

We have default object like:

defaultObj = {
  a: {},
  b: {},
  c: {
    d: {}
  }
};

And target object like this:

targetObj = {
  a: { x: {} },
  b: {},
  c: {
    d: {},
    e: {}
  },
  f: {}
};

Now, I need to perform operation on targetObj by comparing it with defaultObj, and remove all objects that remain empty, but leave every object in targetObj that weren’t originally in default.
Result of operation should look like this:

result = {
  a: { x: {} },
  c: {
    e: {}
  },
  f: {}
}

JavaScript map update subarray to all be the same value

I have created a function to put the same quantity in arrange and then to map over to allocated the value for that month, sorry sounds strange when written down.

But ever time I run it the subarray that is being updated displays the same data in all them:

this.calcTest([
{ id: '001', name: 'First', arrOfStuff: [{ period: '2022-01-01', value: 10 },{ period: '2022-02-01', value: 10 }]},
{ id: '002', name: 'Second', arrOfStuff: [{ period: '2022-01-01', value: 11.11 }]},
{ id: '003', name: 'Third', arrOfStuff: [{ period: '2022-01-01', value: 12.12 },{ period: '2022-02-01', value: 9.99 }]},
{ id: '004', name: 'Fourth', arrOfStuff: [{ period: '2022-01-01', value: 13.13 }] }]);

calcTest(d: any) {
    const testData = [];
    const periods = [
        { period: '2022-01-01', value: '' },
        { period: '2022-02-01', value: '' },
    ];

    d.map((f, indexCheck) => {
        let tempArr = f.arrOfStuff;
        f.arrOfStuff = periods;
        tempArr.map((t) => {
            let i = f.arrOfStuff.findIndex((as) => as.period === t.period);
            f.arrOfStuff[i].value = t.value;
        });
        f.check = indexCheck;
        testData.push(f);
    });
    console.log(testData);
}

this results with:

[{ id: ‘001’, name: ‘First’, arrOfStuff: [{ period: ‘2022-01-01’, value: 13.33 },{ period: ‘2022-02-01’, value: 9.99 }], check: 0},
{ id: ‘002’, name: ‘Second’, arrOfStuff: [{ period: ‘2022-01-01’, value: 13.33 },{ period: ‘2022-02-01’, value: 9.99 }], check: 1},
{ id: ‘003’, name: ‘Third’, arrOfStuff: [{ period: ‘2022-01-01’, value: 13.33 },{ period: ‘2022-02-01’, value: 9.99 }], check: 3},
{ id: ‘004’, name: ‘Fourth’, arrOfStuff: [{ period: ‘2022-01-01’, value: 13.33 },{ period: ‘2022-02-01’, value: 9.99 }], check: 4}]

I would like it to result in:

[{ id: ‘001’, name: ‘First’, arrOfStuff: [{ period: ‘2022-01-01’, value: 10 },{ period: ‘2022-02-01’, value: 10 }], check: 0},
{ id: ‘002’, name: ‘Second’, arrOfStuff: [{ period: ‘2022-01-01’, value: 11.11 },{ period: ‘2022-02-01’, value: ” }], check: 1},
{ id: ‘003’, name: ‘Third’, arrOfStuff: [{ period: ‘2022-01-01’, value: 12.12 },{ period: ‘2022-02-01’, value: 9.99 }], check: 3},
{ id: ‘004’, name: ‘Fourth’, arrOfStuff: [{ period: ‘2022-01-01’, value: 13.33 },{ period: ‘2022-02-01’, value: ” }], check: 4}]

In typescript the filtering the array is not working

filtervalue = {
serviceLine:['cca','ga']
}

this.inProgresDetailsData = [{serviceLine:'cca'}, { serviceLine:'cca'}, { serviceLine:'bca'}]
this.hrResourceDetailsdata= this.inProgresDetailsData.filter(item => {
          for (let index = 0; index < filterValue.serviceLine.length; index++) {
            item.serviceLine == filterValue.serviceLine[index]
          }
        });`

this.hrResourceDetailsdata is empty on filtering

Get the key of a JS Object from the value

I am trying to get the key of a JS Object in Typescript from an input value, the problem is that the values are inside an Array.

This is what I have seen in the case that the value is not in an array:

const exampleObject = {
  key1: 'Geeks',
  key2: 'Javascript'
};

function getKeyByValue(object, value) {
  for (var prop in object) {
      if (object.hasOwnProperty(prop)) {
          if (object[prop] === value)
          return prop;
      }
  }
}

console.log(getKeyByValue(exampleObject,'Geeks')) // key1

This is an example of my object that I want to get the key from:

const exampleObject = {
  key1: ['Geeks','test1','test2'],
  key2: ['Javascript','test3','test4']
};

function getKeyByValue(object, value) {
  for (var prop in object) {
      if (object.hasOwnProperty(prop)) {
          if (object[prop] === value)
          return prop;
      }
  }
}

console.log(getKeyByValue(exampleObject,'Geeks')) // undefined

I need to get the key without using Array.prototype.includes(), because typing the resulting variable as String gives me an error that it may be undefined.

My problem: I don’t know how to go through the array inside the function to find the value and get the key

there is a error when i run ‘npm i ‘ install node_moudles in ‘vue-element-admin’created by PanJiaChen

npm ERR! code ENOENT
npm ERR! syscall spawn git
npm ERR! path git
npm ERR! errno -4058
npm ERR! enoent An unknown git error occurred
npm ERR! enoent This is related to npm not being able to find a file.
npm ERR! enoent

npm ERR! A complete log of this run can be found in:
npm ERR! C:UsersAdministratorAppDataLocalnpm-cache_logs2022-05-19T09_36_53_862Z-debug.log enter image description here

Format user input (thousands separated by “.”) while typing by using javascript

I’m looking to format the input of a text field while the user is typing. Format type has to be thousand separation by “.” like this:

User writes: 1000

Field must show: 1.000

I managed to put this together despite my relatively limited js knowledge, but it won’t format the intended way. Unless the input number is five digits long (for example 10000 shows correctly as 10.000) it won’t work. Four digit numbers are still showing without the “.” seperator.

http://jsfiddle.net/zt4kjrdf/1/

Tried changing input type to number in the html as well, but to no avail.

Could somebody please guide me in the right direction here?

Thanks.

$("#field-to-format").keyup(function() {
  if ($("#field-to-format").val().length == 5) {
    var my_val = $("#field-to-format").val();
    $("#field-to-format").val(Number(my_val).toLocaleString('da'));
  }
});
#field-to-format {
  font-size: 28px;
  text-align: center;
  position: absolute;
  top: 20px;
  left: 20px;
  height: 36px;
  width: 130px;
  border: 2px solid #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="field-1">
  <div class="input">
    <div class="input-wrap">
      <input type="text" id="field-to-format" maxlength="5">
    </div>
  </div>
</div>