How to separate fetch json data in React

I have a component with an array with an icon on it, and when I hover it over, it shows a div with data taken from the .json file. Now {data.strenght} renders all records to every div in the table row and every div looks the same on hovering over the icon. However, I want each div in the line to have the rendered content of the line as it is in the .json file. It is probably best to show it in the pictures.

For now is like this –
https://imgur.com/a/r0SDhy8

And it should be like this –
https://imgur.com/a/axPrBKR

How to do it?

React file

import react from "react";
import funcData from './testData.json';

    function TestFunc() {
        return (
            <div>
                {funcData.map(data => {
                    return (
                        <div key={data.id}>
                            <p>{data.strenght}</p>
                            <p>{data.health}</p>
                        </div>
                    )
                })}
            </div>
        );
    }

    export default TestFunc

JSON file

[
    {   
        "id": "1",
        "strenght": "20",
        "health": "15"
    },
    
    {
        "id": "2",
        "strenght": "555",
        "health": "5"
    }
]

I need to insert a value in an input field of an html form through javascript

HTML code

<div id="formulario">
    <h1>Posicionamento de CEO</h1>
    <form method="POST" style="width: 500px;">   

<div class="form-group">
   <label class="control-label  " for="id_identification">Identificação</label>
        
<div class=" ">enter code here
   <input type="text" name="identification" maxlength="256" class=" form-control" required="" id="id_identification">
</div>
</div>
<div class="form-group">
   <label class="control-label  " for="id_geolocation">Geolocalização</label>
       <div class=" ">
            <input type="text" name="geolocation" maxlength="100" class=" form-control" required="" id="id_geolocation">
</div
        <button type="button" onclick="start()" class="botao">Clique aqui para carregar 
         mapa</button>
    </form>
</div>

Javascript code that opens the map and captures the coordinate when I click on the map.

async function sendCoordsToMyApi(evt) {
    const coords = {
      lat: evt.latLng.lat(),
      lng: evt.latLng.lng()
    };

    console.log("vou enviar as coordenadas para api:", coords);
    alert(JSON.stringify(coords));

I need to enter the coordinate of the constant coords in the form in the input field id=”id_geolocation”
can you help me?

Moving ball at constant rate with angle

I am coding a small game in JavaScript and I am running into a math problem. I am trying to move an object towards the location that I just clicked. I am able to successfully do this with the code below. However I am having difficulty figuring out how to make the velocity constant. If I click close to the object that I am shooting from, the difference in the X/Y is small so dx/dy is slow. If I click far away the dx/dy has high values, so it moves a lot faster.

Here is the code that I have so far.

let relativeXY = relMouseCord(e);
let rise = relativeXY[1] - pOne.posY; //<-- This is the distance between the Y coords
let run = relativeXY[0] - pOne.posX; //<-- This is the distance between the X coords

let angle = Math.atan2(rise,run)*180/Math.PI 
console.log('tan angle ' + Math.tan(angle))
console.log('acutal angle '+ angle)

bullet.x = pOne.posX
bullet.y = pOne.posY

tempdx = run * 0.02     //Math.cos(angle)
tempdy = rise * 0.02    //Math.sin(angle)

I attempted to use cos and sin to normalize the speed and was able to make the velocity constant, but the direction of the projectile was incorrect.

Forward servlet response to React js

I have a complex requirement where I need to implement react js in a servlet jsp application.

The entire application developed in servlet jsp. I need to replace a particular functionality with React js.

Current functionality:
Click the link in a JSP page. It makes a servlet call and returns list of data that will be displayed in a table in the new JSP page.

New Requirement:
Click the link in a JSP page. It makes a servlet call and returns a json response, which needs to be consumed by React JS.

My concern is that the servlet can’t be a standalone service as it requires parameters coming from JSP request and fetch the details based on the request parameters and return json.

How do I achieve this as this seems to be complex?
The reason I want to implement react js is to have modern datatable features.

Power BI Embedded : Cant doCross Filtering selecting multiple rows on a table visual pressing CTRL

Hello I have the following problem:

We have embedded different visuals from a PBIX file onto a asp.net core razor view.

We have achieved that when a user clicks on a row in a table visual, detect the item and corssfilter the other embedded visuals as the user clicks.

On the Power BI environment you can do the same, but by pressing the CTRL key, you can select multiple rows and then it will filter the whole visuals on that page.

As we achieved the crossfiltering selecting just one we thought it would do the same by pressing CTRL, the problem is that PowerBI Embedded visual is not detecting the CTRL key and it is not actually detecting that we are selecting more than one row and it changes the whole filters to the first selected row.

We are detecting via JS the CTRL key

enter image description here

After we click in more than one row or item, the event is lost and we can’t get the list that the user was selecting:

enter image description here

Best (functional) way in React to lift state an arbitrary number of levels?

I saw this post from 2017 where it was asked how to lift state up two levels in react. The answer used this in the context of an OOP design. Five years later, components can be written in functional programming, largely omitting usage of the this keyword.

What’s the simplest way to lift state up any arbitrary number, n, levels? Is this something best accomplished with tools like redux or is vanilla React sufficient?

For example, I’m unsure how to best pass deleteItemHandler (noted in inline comments) from App to Item, passing through Display.

function App() {
  const [todoList, todoListSetter] = useState([]);

  const addTodoHandler = (item) => {
    todoListSetter((prevItems) => {
      return [item, ...prevItems]
    });
  };

  const deleteItemHandler = (item) => { //Level 1
    todoListSetter((prevItems) => {
      return prevItems.filter(elem => elem !== item)
    });
  };
  
  return (
    <div >
      <Display removeItem={deleteItemHandler} items={todoList} /> //Level 1->2      
      <Form onSaveItem={addTodoHandler}/>
    </div>
  );
};

const Display = (props) => {
  props.items.map((item) => {
    return(
    <div>
      <Item deleteItemHandler={props.removeItem} value={item}/> //Level 2->3
    </div>)
  });
};

const Form = (props) => {
    
    const [newItem, setNewItem] = useState("");
    const newItemHandler = (event) => {
      setNewItem(event.target.value);
    };   
    
    const submitHandler = (event) => {
        event.preventDefault();
        props.onSaveItem;

    };
    
    return(
        <div>
            <h2>Add item to todo list</h2>
            <form onSubmit={submitHandler}>
                <label>New Item</label>
                <input type='text' onChange={newItemHandler} />
            </form>
        </div>
    ) 
};

const Item = (props) => {
    
    return(
        <div>
            <h1>{props.value}</h1>
            <button onClick={props.deleteItemHandler}>Delete Item</button> //Level 3
        </div>
    )
};

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);

filter an array of objects in javascript, with siblings that match on a common key value

Suppose I have a javascript array of objects that looks like this:

[
    {
        "title": "The Great Peace",
        "copyversion": 1
    },
    {
        "title": "History of World War II",
        "copyversion": 1
    },
    {
        "title": "Crime and Punishment",
        "copyversion": 2
    },
    {
        "title": "War and Peace",
        "copyversion": 2
    }
]

Now, suppose that I have a search string, like “War” or “and”. I want to get an array of objects where “title” contains the search string (case insensitive), but I want to ALSO include any sibling values with matching “copyversion” values.

For example:

Search string of “Great” should yield the below result, because even though “History of World War II” does not have “Great” in it, it matches the copyversion of something that does.

[
    {
        "title": "The Great Peace",
        "copyversion": 1
    },
    {
        "title": "History of World War II",
        "copyversion": 1
    }
]

Another example:

Search string of “Peace” would yield the original array. “History of World War II” is included because it has the same copyversion value as “The Great Peace”, and “Crime and Punishment” is included because it has the same copyversion as “War and Peace”

[
    {
        "title": "The Great Peace",
        "copyversion": 1
    },
    {
        "title": "History of World War II",
        "copyversion": 1
    },
    {
        "title": "Crime and Punishment",
        "copyversion": 2
    },
    {
        "title": "War and Peace",
        "copyversion": 2
    }
]

If no matches are found, then an empty array would result.

I’m looking for a reasonable fast way to do this. I’m fine with pure javascript or a library like lodash.

return what was not found in array in MongoDB

say my database collection has

* user collection*
[
{id:'1'}
{id:'2'}
]

I have an array of object

[
{id:'1'}
{id:'2'}
{id:'3'}
]

I want the object that was not found in the collection.

I want

[

{id:'3'}
]

I’m currently have this

 const records = await dbo
        .collection('some_collection')
        .find({
          'id': { $in: newArr },
        })
        .toArray();

I’m a bit stumped on what to do! … hope someone can help Thanks!

Using Promise when extracting data from Supabase into React

I have an async function that gets data from my Supabase database, that when called, returns a promise with the correct data that I have queried, but when I try to call this function in a React component, I don’t know how to extract the data from the Promise and just get the string that I queried.

I understand that you can not get the result of a promise in the same scope as you call it, but I’m not sure how I would get around this.

My code:

export async function getUserValue(uuid, value) {
    const { data, error } = await supabase
        .from('users')
        .select('username').eq("id", "8f1693d3-c6d9-434c-9eb7-90882ea6ef28"); // hard coded values for testing purposes
    return data;
}

Where I call it:

...
async function Sidebar(props) {
    console.log(getUserValue("", ""))

    return (
        <div className={"sidebar"}>
            <div className="sidebar-main">
                <img className={"sidebar-main-picture"} src={profile_picture} alt="pfp"/>
                <p className={"sidebar-main-name"}>Test</p>
...

Resultresult

Can i make my bot join other twitch channels with a command with TMI?

require('dotenv').config(); 

var config = require('./config');

const tmi = require('tmi.js');

const client = new tmi.Client({
    options: { debug: true },
    identity: {
    username: process.env.BOT_USERNAME,
    password: process.env.OAUTH_TOKEN
    },
    channels: [ config.channel ]
});

client.connect();

client.on('connected', (address, port, channel ) =>{
    client.action(config.channel, config.connectedmessage)
});

client.on('chat', (channel, user, message, self) => {
    if (message ==='!join'){
        client.action(config.channel, `${user['display-name']} ${config.joinmessage}`);

        let newchannel = user['display-name'].toLowerCase()
        console.log(newchannel)
    };
});

So i was thinking i would get the new channel name where to connect the bot by making people type !join in the main channel . So i would get their twitch name channel with this function, but i wonder if anyone knows what i can do there to make my bot connect to that channel

How do I configure parcel to exit build with an error if eslint does not validate

I’m building a react app with parcel. I have an eslint config set up that I like, and use VSCode tools to catch eslint errors and fix them as I code. The app builds correctly as of now. So all that is fine.

However, as an added precaution, I would like to set up parcel to run eslint, using my config, and to halt the build process and output an error when I havent followed the eslint rules, either when running dev server or building for production.

I’m aware of this npm package from googling, but the package doesnt have a readme, and i can’t find setup instructions in the parcel docs: https://www.npmjs.com/package/@parcel/validator-eslint

For reference I am using parcel 1.12.3 but would be open to changing to parcel 2.x.x if that is neccesary.

Thanks!

turn html into string but keep all html tags javascript

I have an array of html. I am trying to run remainderHtml.toString() but result is

[object HTMLLabelElement],[object HTMLLabelElement],[object HTMLLabelElement]

How can I run a toString command (or any other command) and create an html string Exactly like my array? I do not want to remove the tags, or extract any data, just plain want to make this array of html one long connected string…

Here is my array of html from the console.log

(4) [label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3, label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3, label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3, label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3]

When I put the above into a variable called remainderHtml and try to run a toString() on it, I get [object HTMLLabelElement],[object HTMLLabelElement],[object HTMLLabelElement]

When I click on the arrow in the console to show the html array I get this below


0: label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3
1: label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3
2: label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3
3: label.p-1.font-weight-bold.bg-primary.ml-2.text-white.rounded-capsule.shadow-none.fs--3
length: 4

Convert PHP array to Javascript Ojbect

hi I’m trying to create a JavaScript object based on a template I received as a test. I use Ajax to get the data from my database but i cant seem to create the object.

 $(document).ready(function() {
          
          $.ajax({
              type: 'POST',
              url: 'fetch.php',
              datatype:'JSON',
              success: function(response) {
               
                var test=JSON.parse(response);
                var products = {};                 
                for (var x = 0; x < test.length; x++) {
                  products[x] = {productName: test[x]['name']};
                  products[x] = {category: test[x]['category']};
                  products[x] = {price: test[x]['price']};
                 
                }

                


              }
          });
     
  }); 

I’m trying to create something like this object below

products = {data: [

{
  productName: "test_item_1",
  category: "category1",
  price: "49",
  image: "test_image.jpg",
},
{
  productName: "test_item_2",
  category: "category3",
  price: "99",
  image: "test_image.jpg",
},
{
  productName: "test_item_3",
  category: "category3",
  price: "29",
  image: "test_image.jpg",
},],}; 

Failed to process internal error: entered unreachable code: assign property in object literal is invalid

I’m new to JSX, I’m building a Nextjs app, and I’m having this irritating error:
“failed to process internal error: entered unreachable code: assign property in object literal is invalid”

This is my index.js

import CardsContainer from "../components/layout/CardsContainer";
import SideNav from "../components/layout/side-nav/SideNav";
import TopNav from "../Components/layout/top-nav/TopNav";


const cards = [
  {id = 1, city = "Riyadh", gender = "Male", image = "1"},
  {id = 2, city = "Riyadh", gender = "Male", image = "1"},
  {id = 3, city = "Riyadh", gender = "Male", image = "1"},
  {id = 4, city = "Riyadh", gender = "Male", image = "1"},
  {id = 5, city = "Riyadh", gender = "Male", image = "1"},
  {id = 6, city = "Riyadh", gender = "Male", image = "1"}
];

export default function Home() {
  
  return (
    <Fragment>
      <TopNav />
      <SideNav/>
      <CardsContainer cards={cards}/>
    </Fragment>
  );
}

This is my CardsContainer.js

export default function CardsContainer(props) {
  //const cards = props.cards;
  const cards = props.cards;

  return (
    <div class="w-9/12 bg-gray-400">
      {cards.map((card) => {
        return (<CatCard cat={card} />);
      })}
    </div>
  );
}

And this is my CarCard.js

import Image from "next/image";
import Link from "next/link";

export default function CatCard(props) {
  
  const id = props.cat.id;
  const city = props.cat.city;
  const gender = props.cat.gender;
  const image = props.cat.image;

  return (
    <Link href={`/catdetails/${id}`}>
      <a>
        <div
          class=" p-2 pb-5 bg-white w-80 rounded-xl border-2"
          id="card-with-image"
        >
          <div class="rounded-xl w-full h-52 overflow-hidden">
            <Image
              className="min-h-full object-cover object-left"
              src={`/images/cats/${image}.jpg`}
              alt="Tumbnail Image"
              width="300"
              height="200"
            />
          </div>
          <div class="px-2 my-4">
            <h2 class="my-3 font-medium text-lg">City:</h2>
            <p class="my-3 text-base text-[#425466]">
              {city}
            </p>
          </div>
          <div class="px-2 my-4">
            <h2 class="my-3 font-medium text-lg">Gender:</h2>
            <p class="my-3 text-base text-[#425466]">
              {gender}
            </p>
          </div>
        </div>
      </a>
    </Link>
  );
}

What do you guys think? I have fiddled with all brackets and curly brackets (and semi-colons), nothing resolved.