Display the info into a div when clicking the table elements in React

enter image description here

I need to display the info from one div into another when I click on any element of the table. When I click on the table it shuffles between random data (I need it in the other div not to shuffle).

This is my vehicles.js

import React from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Card, Button} from 'react-bootstrap';
import {faker} from '@faker-js/faker'
import VehicleList from './VehicleList';

class Vehicles extends React.Component{
  constructor(props){
    super(props);
    this.vehicle = []
    this.state = { 
      manufacturer: faker.vehicle.manufacturer()}
    
    }
erateVehicle() {
    let manufacturer = faker.vehicle.manufacturer()

    return {
      manufacturerN: manufacturer,
    }
  }

  changeManufacturer=()=>{
    this.setState({
      manufacturer: {manufacturer: faker.vehicle.manufacturer()}
    });
  }

  vehicles() {
    return this.props.vehicles.map((vehicles) => <VehicleList vehicles={vehicles}
                                                key={vehicles.manufacturer}
                                                onContactSelected={this.props.onContactSelected} />)
  }

  render(){
  return(

<div style={{ display: 'block', width: 400, padding: 30 }}>
      <Card className="text-center">
      <h2>{this.state.manufacturer}</h2>
          <button
          type = 'button'
          onClick={this.state.changeManufacturer}
          >shuffle</button>
        <Card.Body onClick={this.handleGenerateVehicle}>
          <Card.Title>No Vehicle Selected</Card.Title>
          <Card.Text>
            Click a vehicle to see more details
          </Card.Text>
        </Card.Body>
        </Card>
      <br></br>
        <Card id='test' style={{ width: '18rem' }}>
          <Card.Img variant="top" src={`https://via.placeholder.com/180x150?text=${faker.vehicle.vehicle()}`} />
          <Card.Body>
          <Card.Title>{faker.vehicle.vehicle()}</Card.Title>
            <Card.Text>
            This is a wonderful {faker.vehicle.fuel()}-powered {faker.vehicle.color()} {faker.vehicle.type()}.
            </Card.Text>
            <Button variant="primary">Buy now!</Button>
          </Card.Body>
      </Card>
</div>
)
}
}

export default Vehicles

and this is my vehicleList.js (where the data is generated upon loading the page)

import React from 'react'
import {faker} from '@faker-js/faker'
import ListGroup from 'react-bootstrap/ListGroup';
import 'bootstrap/dist/css/bootstrap.min.css';

class VehicleList extends React.Component {
  constructor(props){
    super(props);
    this.state = {vehicles : []}
    this.state = {
      manufacturer: faker.vehicle.manufacturer(),
      model: faker.vehicle.model(),
      type: faker.vehicle.type(),
      fuel: faker.vehicle.fuel(),
      vin: faker.vehicle.vin(),
      color: faker.vehicle.color()
    };
  };

  vehicles() {
    for (let i = 0; i < 10; i++) {
      this.vehicles().push({
      });
    }
  }

  changeManufacturer=()=>{
    this.setState({
      manufacturer: 'hhhh'
    });
  }

  render(){
   return (
  <div style={{ display: 'block', width: 400, padding: 30 }}>
            <td>{this.setState.vehicles}</td>
        <ListGroup className="w-300 align-self-start">
        <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
          <ListGroup.Item action active={ '' } onClick={ () =>this.changeManufacturer()}>
          {faker.vehicle.manufacturer()} {faker.vehicle.model()}</ListGroup.Item>
        </ListGroup>
    </div>
  );
  }
}

export default VehicleList

Any help is highly appreciated!!

Minified React error #31 with sharepoint online using React + redux

I’m facing an error that has been searching by myself for 2 days. But currently It’s still not resolved, so I came here to ask If anyone ever faced this?

I’m using Redux toolkit in a sharepoint online project for passing data to each other components.

The first component worked perfectly, but when I use useSelector function for the 2nd one, this error appearsenter image description here

Although when I tried using console.log for each component, both are still receiving the data but
using data for the 2nd component will happen this error.

So has anyone ever faced this please help me out~, here is my codes

slice:

import { createSlice } from '@reduxjs/toolkit';

export interface titleState {
  title: string;
}

const initialState: titleState = {
  title : 'Your title'
};

export const titleSlice = createSlice({
  name: 'title',
  initialState,
  reducers: {
    SET_TITLE: (state, action) => {
      state.title = action.payload;
    }
  }
});

export const { SET_TITLE } = titleSlice.actions;

export default titleSlice.reducer;

store

import { configureStore } from '@reduxjs/toolkit';
import titleReducer from "../features/titleSlice/titleSlice";
export const store: any = configureStore({
  reducer: {
    title: titleReducer
  },
});

export type RootState = ReturnType<typeof store.getState>;
export type AppDispatch = typeof store.dispatch;

first component:

import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";

const FirstComponent: FunctionComponent<FirstComponent> = (
  props
) => {
  const STATE_TITLE = useSelector((state: RootState) => state.title);
  console.log(STATE_TITLE);
  const dispatch = useDispatch<AppDispatch>();
const handleTitle = (e) => {
    dispatch(SET_TITLE(e.target.value));
    setTitle(e.target.value);
  }
return (
  <div>
   <textarea
     onChange={handleTitle} //works fine
   />
  </div>
}

second component:

import { useSelector, useDispatch } from "react-redux";
import { AppDispatch, RootState } from "../../../../redux/store/store";
const SecondComponent: FunctionComponent<ISecondComponentProps> = (props) => {
  const TITLE_STATE = useSelector((state: RootState) => state.title)
  console.log(TITLE_STATE)
return (
  <div>
   {YOUR_TITLE} //this line happens error
  </div>
)

and here is the error from development tab : enter image description here

Set text value multiple time using jquery

I want to set the text value of the process-all class multiple time. When I click the button it will executing the ajax request and the text changed to Please Wait. And when the ajax process is finished, I want to change the text to Completed. I cannot changed it inside ajax success or complete because the function is general & used for many request (not only for this one).

I’ve tried something like code bellow but still not working:

    $(".process-all").click(function (i, o) {
        $(this).prop('disabled', true);
        $(this).text('Please Wait...');

        // the ajax process
        setTimeout(function () {
            $(".group-payroll").each(function(i, obj){
                let thisObj = $(obj).find(".process-attendance");
                    processAttendance(obj, thisObj);
                });
        }, 3);

        $(this).text('Completed');
    });
<a href="javascript:void(0)" class="btn btn-sm mb-2 process-all">Process All</a>

How do I correctly send request post headers using fetch?

Access to fetch at ‘backend’ from origin ‘frontend’ has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

I continue to get this error no matter what I do in my application. I am building a react + express application and I have no idea what to do anymore.

This is my backend code that has to do with cors.

app.use(cors({
    origin: "*",
    methods: 'GET,HEAD,OPTIONS,POST,PUT',
    allowedHeaders: "Origin, Content-Type, Accept"
}));
app.options('*', cors()) 
app.use(function (req, res, next) {
    res.setHeader('Access-Control-Allow-Origin', 'frontend');
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type,accept');
    next();
});

This is the frontend code using fetch that is making a post request.

fetch('backend', {
          method: 'post',
          headers: {
            'Accept': 'application/json',
                      'Content-Type': 'application/json',
                  },
          body: JSON.stringify({
            downloadLink: link,
            password: password,
            user: true,
            apiKey: apiKey
          })

I’m so lost as theoretically there should be no problems with this. I have seen all the posts that people have made before and none of them work. Any idea why? Thanks.

EDIT: I should mention that it works perfectly on localhost. Just fails when going through nginx reverseproxy and cloudflare.

How to process options before commands in commander.js?

This is my code:

const {program} = require('commander');
program
  .option('--foo')
  .command('bar').action((str, opts) => {
    console.log('bar!');
  })
program.parse();
if (program.opts().foo) {
  console.log('foo!');
}

I run it like node test.js --foo bar and it prints:

bar!
foo!

I want it to print foo! first. How can I do this?

readAsDataUrl converting to octet-stream instead of pdf

I am getting a blob data from a RESTFul endpoint and then I need to convert it to base64 string with file type as application/pdf however its converting it to application/octet-stream.

Here’s what my codes does:

const getBytesData = () => {
    if (user) {
      getInvoicePDFStringByInvoiceId('129', user.user.token).then((data) => {
        if (data.blob) {
          const reader = new FileReader();
          reader.readAsDataURL(data.blob);
          reader.onloadend = () => {
            var base64data = reader.result.replace('octet-stream', 'pdf');
            console.log('Pdf loaded:- ', base64data);
            setPDFLoaded(base64data);
            return;
          };
        } else {
          console.log('Error happened from API = ', data.error, data.message);
        }
      });
    }
  };

Can someone help me understand what could solve this issue?

Javascript multiple select2 does’nt work on click event

I want to click event an select2 .. each button click will create a select box with select2 function libraries. And it will appear only a simple selectbox.

 $('.main_select2').select2({
    placeholder: 'Selection Box',
    allowClear: true
  });
$('#add_select').on('click', function() {
    $('.for_select').append( 
    '<div class="c-input c-input--select c-input--icon">'
          + '<select class="select2 main_select2">'
          + '<option>Choose 1</option>'
          + '<option>Choose 2</option>'
          + '<option>Choose 3</option>'
          + '</select>'
      + '</div>');
  })
.main_select2{
  width:200px;
  margin-top:10px;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.0.0/select2.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/2.1.0/select2.min.js"></script>

<button type="button" id="add_select">Add Select2</button>
<div class="for_select">
  <div class="c-input c-input--select c-input--icon">
      <select class="select2 main_select2">
          <option>Choose 1</option>
          <option>Choose 2</option>
         <option>Choose 3</option>
      </select>
  </div>
</div>

Is there any possible to do this with multiple class in select2.. Thanks

Loop over a list of ids and foreach id get data from api

Loop over a list of ids and foreach id get data from api but, i can make only 40 requests per 10 seconds, i’m getting data from tbdb but i’m getting kicked by the api here is my code

Popular.findAll({ limit: 25 }).then((filmes) => {

for (let index = 0; index < filmes.length; index++) {
    const element = filmes[index];
    const id_filme = element.id_filme;

i get each movie id so i can make requests to the api with this function..

function fetchdata(id_filme) {
  setTimeout(function () {
    axios
      .all([
        axios.get(
          `https://api.themoviedb.org/3/movie/${id_filme}?api_key=${process.env.API_KEY}&language=pt-BR`
        ),
        axios.get(
          `https://api.themoviedb.org/3/movie/${id_filme}/videos?api_key=${process.env.API_KEY}&language=pt-BR`
        ),
      ])
      .then(
        axios.spread(function (detalhes, linksyt) {
          var filme = detalhes.data;
          var youtube = linksyt.data;
          // console.log(filme, youtube);
          var filmesLista = new Array();
          const title = filme.title;
          const filmeid = filme.id;
          if (Object.keys(filme.genres).length === 0) {
            var genre = filme.genres;
          } else {
            var genre = filme.genres[0].name;
          }
          const overview = filme.overview;
          const poster_path =
            "https://image.tmdb.org/t/p/w500" + filme.poster_path;
          const release_date = filme.release_date;
          const vote_average = parseFloat(filme.vote_average);
          const backdrop_path =
            "https://image.tmdb.org/t/p/original" + filme.backdrop_path;
          const imdb_id = filme.imdb_id;
          const runtime = filme.runtime;

          if (Object.keys(youtube.results).length === 0) {
            var trailer = "";
          } else {
            var trailer =
              "http://www.youtube.com/watch?v=" + youtube.results[0].key;
          }

          filmesLista.push([
            filmeid,
            title,
            genre,
            overview,
            poster_path,
            release_date,
            vote_average,
            backdrop_path,
            imdb_id,
            runtime,
            trailer,
          ]);
          console.log(filmesLista);

          filmesLista.forEach((i) => {
            const filmeid = i[0];
            const title = i[1];
            const genre = i[2];
            const overview = i[3];
            const poster_path = i[4];
            const release_date = i[5];
            const vote_average = i[6];
            const backdrop_path = i[7];
            const imdb_id = i[8];
            const runtime = i[9];
            const trailer = i[10];

            Detalhes.create({
              id_filme: `${filmeid}`,
              title: `${title}`,
              genre: `${genre}`,
              release_date: `${release_date}`,
              vote_average: `${vote_average}`,
              imdb_id: `${imdb_id}`,
              runtime: `${runtime}`,
              overview: `${overview}`,
              poster_path: `${poster_path}`,
              backdrop_path: `${backdrop_path}`,
              trailer: `${trailer}`,
            });
          });
        })
      );
    o++;
    if (o < 25) {
      fetchdata(id_filme);
    }
  }, 10000);
  console.log("INSERIDO NO BANCO");
}
fetchdata(id_filme);

the code works but, works so fast and i get kicked every time i run with more than 40 ids.. i’m strugling on just make 40 request every 10 secconds. anyone can help me please?

Compare 2 array of string in Javascript with regex

I have 2 arrays

const arrayFirst = ["helloFriendJohn", "I'm good today", "Friend", "how about you?"];
const arraySecond = [/helloFriend.*/g, /friend/g];

ArrayFirst contains pure string, arraySecond contains regex of arrayFirst, so how could I compare 2 array.

How can I compare these 2 string arrays, currently the 2nd element of arrayFirst is attached to element 1st of arraySecond, but the expected result is not like that.

I want to pair element 1st arrayFirst with element 1st arraySecond, similarly element 3th arrayFirst with element 2nd of arraySecond. (I’m talking about the length of the string).
So is there any way to achieve this?

How can I turn an array object into an object?

I want to put an array object called hello into a constant called answer. At this time, I want to change the key value of the answer to the value key of hello and the value of the answer to the label value of hello.

how can i do that? i was thinking object entries but i couldn’t do that….
is it possible??

this is my code

const hello = [
{ label: 'one', value: 'Tangerinefeed' },
{ label: 'two', value: 'dryexamfeed' },
{ label: 'three', value: 'wetfeed' },
{ label: 'forth', value: 'sawdust' },
{ label: 'five', value: 'etc' },
] ;

expected answer

const answer = {Tangerinefeed: 'one', dryexamfeed: 'two', wetfeed: 'three', sawdust: 'forth', etc: 'five'}

Create multi bar/ muli series highchart in laravel

I want to make a chart with multi series/ multi data with highcharts in laravel, but I always fails, this is my expectations
enter image description here
Tokyo, London, etc. there are replaced with the name of my product category

this is my controller:

<?php

namespace AppHttpControllers;

use AppModelsCategory;
use IlluminateHttpRequest;
use IlluminateSupportFacadesDB;
use PHPUnitTextUIXmlConfigurationGroup;

class DashboardController extends Controller
{
    public function index()
    {
        $category = Category::select('name')->pluck("name");

        $total = Category::select(DB::raw("SUM(total) as total"))->GroupBy(DB::raw('MONTH(created_at)'))->pluck('total');

        $bulan = Category::select(DB::raw("MONTHNAME(created_at) as bulan"))->GroupBy(DB::raw('bulan'))->pluck('bulan');


        return view('admin.dashboard', compact('category', 'total', 'bulan'));

    }
}

and this is html and javacript code

@section('content')
<h1 class="gray">Dashboard</h1>

<figure class="highcharts-figure">
    <div id="container"></div>
    <p class="highcharts-description">
        A basic column chart compares rainfall values between four cities.
        Tokyo has the overall highest amount of rainfall, followed by New York.
        The chart is making use of the axis crosshair feature, to highlight
        months as they are hovered over.
    </p>
</figure>

@section('javascript')
    <script src="https://code.highcharts.com/highcharts.js"></script>
    <script src="https://code.highcharts.com/modules/exporting.js"></script>
    <script src="https://code.highcharts.com/modules/export-data.js"></script>
    <script src="https://code.highcharts.com/modules/accessibility.js"></script>

    <script type="text/javascript">

        let category = <?php echo json_encode($category) ?>;
        let total = <?php echo json_encode($total) ?>;
        let month = <?php echo json_encode($month) ?>;

        console.log(category, total, month);

        Highcharts.chart('container', {
            chart: {
                type: 'column'
            },
            title: {
                text: 'Monthly Average Rainfall'
            },
            subtitle: {
                text: 'Source: WorldClimate.com'
            },
            xAxis: {
                // categories: ["Jan", "Feb", "Mar", "Apr", "Mei", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"],
                caegories : month,
                crosshair: true
            },
            yAxis: {
                min: 0,
                title: {
                    text: 'Rainfall (mm)'
                }
            },
            tooltip: {
                headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
                pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
                    '<td style="padding:0"><b>{point.y:.1f} mm</b></td></tr>',
                footerFormat: '</table>',
                shared: true,
                useHTML: true
            },
            plotOptions: {
                column: {
                    pointPadding: 0.2,
                    borderWidth: 0
                }
            },
            series: [{
                name: category,
                data: total
            }]
        });

    </script>
@endsection

@endsection

and this is the result I get enter image description here

How do I repopulate multiple textareas with their specific user input (saved as an array in localStorage) on refresh?

I’m building a scheduling web app, and it shows a table of rows with time of day, a text area, and a save button side by side for each hour of the day. The user can type their info into the textarea next to a given time, click the button, and it will save their input to localStorage. On refresh, the localStorage still shows the saved user input when I console.log it, but it won’t repopulate the textareas with it. I want their user input to still show up in those textareas when they refresh the page, but something about how I’m using localStorage.getItem doesn’t seem to be working. I’d love some help, and thank you!

(Sorry in advance that the images are posting as links, it won’t let me embed them)

Here’s an example of the HTML I have for each row of the table, which includes the textarea.

This is my current JS for adding the user input to localStorage.

And this is all I’ve got for my getItem function so far, which is what I need help fixing!

Trying to solve a MySql error via XAMPP, on my Macbook. All the tutorials and link online are for Windows

I am trying to solve multiple errors that I receive everytime I try to access “localhost/phpmyadmin” on my browser.

I am using XAMPP to access MySql for a webapp that I am developing for fun. I am kinda new to this and am extremely confused as to why this is happening, as it initally allowed me to create a database but I am suddenly locked out?

It’s so frustrating.

I’ve attached a picture of the error I am receiving and also what my code looks like.

Error

Code

Please help me!!

How Can I Determine the Length of a String Encoded With (Node Crypto) Scrypt?

I’m encrypting the passwords on my site using the crypto library from Node, specifically crypto.scrypt. For instance:

import { randomBytes, scrypt, timingSafeEqual } from 'crypto';
import { promisify } from 'util';

const scryptAsync = promisify(scrypt);

const hashPassword = password => {
  const salt = randomBytes(16).toString('hex');
  const buffer = await scryptAsync(password, salt, 64);
  return `${buffer.toString('hex')}.${salt}`;
}

If I have a maximum password size of N, how big of a database column do I need to store the encrypted passwords generated from the above? Obviously my encrypted passwords are going to be bigger than the original, but I haven’t been able to find out how much bigger.

Also, I imagine it has something to do with the arguments … but I’m unclear on the details. For instance, I pass scrypt a “keylen” argument of 64, but the documentation doesn’t make it clear what that “keylen” is exactly, or whether it impacts the encrypted string’s size.

Loadsh isEqual function is causing application freeze

I am creating a react component, and it do the default export a do the following line:

React.memo(MyReactComponent, isEqual)

The isEqual function is from loadsh lib. My application constantly tries to update the component props at 10 Hz. However, from time to time my application freezes executing the isEqual function from loadsh. Do you guys have ideas for what could cause it?