Create responsive drag and drop dashboard in React

I am trying to create a dashboard where users can drag and drop widgets within the dashboard to any position they’d like. I’ve seen other examples similar but they all seem to have predefined elements.
In my case, the user can create and remove elements on the dashboard and move them to any point on the board.
My question is, what would be the best way to create a dashboard like this that supports the dragging and dropping of an element anywhere on it. Also, how can I save this info?

Thanks in advance.

Change Link To value on condition

I’m trying to implement a login page for my app.
When the login button is clicked, a fetch is called and tries to login with the user’s info.
If the login succeeds, login button’s value updates to be the homepage, else it changes back to the login page address.
Any idea on how to make it work?
I tried <Link to={redirect?"/home":"/"}> but it didn’t do anything, and I also tried using a state prop which holds the link value but still had problems with it.

Detect data changes and update redux persist?

I know we can use redux-persist for saving our redux store in localstorage.
Let’s say I have a API data which I want to save in redux-persist.
But problem is that let’s say this data can be changed any time.

For example; I have a users list and I don’t want to get this users list on every page refresh so I decide to save them in redux-persist. But what will be happen if the new user added to db and I want to see this user also in my users list. How can I do this ? Is that even possible ? It’s look like silly question I know because if I want to detect new users I have to make a call anyway 😀 I just want to know is there anyway for that ?

Angular: How to bind an array model attribute to a copy able div element

First of all I apologize for the bad title, I wasn’t sure exactly how to describe it.

I have this div for the user to enter contact information pertaining to a “program” for which the user also entered data. Right now you can only enter 1 set of contact information in this div:

<div id="programContactContainer" class="container">

      <div id="programContact">
        <div class="form-group mt-2">
          <label>Name</label>
          <input type="text" class="form-control" id="contactName"
                 required
                 [(ngModel)]="model.contact.name" name="contactName">
        </div>

        <div class="form-group mt-2">
          <label>Email</label>
          <input type="text" class="form-control" id="contactEmail"
                 required
                 [(ngModel)]="model.contact.email" name="contactEmail">
        </div>

        <div class="form-group mt-2">
          <label>Phone</label>
          <input type="text" class="form-control" id="contactPhone"
                 required
                 [(ngModel)]="model.contact.phone" name="contactPhone">
        </div>
        <br>
        <hr/>
      </div>
    </div>

    <input class="btn btn-primary" type="button" value="Add another contact" (click)="cloneContactDiv()">

If you click that button it adds an identical div below the existing one so the user can enter multiple contacts.

Code for copying div:

  cloneContactDiv(){
    const myDiv = document.getElementById(('programContact'));
    const divClone = myDiv.cloneNode(true);
    document.getElementById('programContactContainer').append(divClone);
  }

This is the model for both the program and the contact info (I know that not all of this is used in the question but I thought it might help):

export class ContactModel {
  name: string;
  email: string;
  phone: string;
}

export class ProgramModel {
  category: string;
  name: string;
  description: string;
  shortDescription: string;
  support: string [];
  address: string;
  location: [];
  areaServed: string;
  baseLocation: string;
  website: string;
  topic: string [];
  ownerLid: string;
  keywords: string[] = [];
  startDate: Date;
  endDate: Date;
  notification: boolean;
  daysForNotice: number;
  filter: string [];
  active: boolean;
  /// Contacts
  contact = new ContactModel();
  /// Departments
  departmentContact = new ContactModel();
}

If I change contact = new ContactModel(); to contact: ContactModel[] = []; then I can save an array of them, but I have no idea how to handle this in the html page. As you can see, the contact info was bound like this: [(ngModel)]="model.contact.name", but how do I handle that when there is more than 1 and an unknown number of how many?

Access Array Values in Typescript

I have this service_transcript array and this.service.getValue() returns the arr_value array

const service_transcript=this.service.getValue();


public arr_value=[];
  getValue()
  {
    return this.arr_value;
  }

when i console.log(service_transcript[0]); getting undefined

enter image description here

Display data of chart.js from data in html jquery

I using SignalR by Js to update my data from the database and put my data to Chart.js . But maybe my syntax goes wrong. Could you help me to edit my code? Thank you very much.

My signalR function code :

<script type="text/javascript">
    $(function () {
        //Proxy created on the fly
        var cus = $.connection.cusHub;

        //Declare a function on the job hub so the server can invoke
        cus.client.displayValue = function () {
            getData();
        };

        //Start the connection
        $.connection.hub.start();
        getData();
    });

    function getData() {
        var $tbl = $('#tblValue');
        $.ajax({
            url: $("#Get").val(),
            type: 'GET',
            datatype: 'json',
            success: function (data) {
                $tbl.empty();
                $.each(data.listCus, function (i, model) {
                    $tbl.append
                        (
                            //'<tr>' +
                            //'<td>' + model.DeviceID + '</td>' +
                            //'<td>' + model.Value + '</td>' +
                            //'</tr>'
                             model.Value
                        );
                });
            }
        });
    }
</script>

I display data in HTML by ID “tblValue” and my browser is “1000” :

                            <h2 id="tblValue"> </h2>

And I get data with getElementByID from id “tblValue” into data of Chart.js but it is null and there is nothing in my chart :

<script>
    var ctx = document.getElementById("percent-chart2");
    var my_val = document.getElementById('tblValue').innerHTML;
    var vals = parseFloat(my_val);
    if (ctx) {
            ctx.height = 209;
            var myChart = new Chart(ctx, {
                type: 'doughnut',
                data: {
                    datasets: [
                        {
                            label: "My First dataset",
                            data: [vals , vals, vals ],
                            backgroundColor: [
                                '#00b5e9',
                                '#fa4251',
                                '#006400'
                            ],
                            hoverBackgroundColor: [
                                '#00b5e9',
                                '#fa4251',
                                '#006400'
                            ],
                            borderWidth: [
                                0, 0, 0
                            ],
                            hoverBorderColor: [
                                'transparent',
                                'transparent',
                                'transparent'
                            ]
                        }
                    ],
                    labels: [
                        'STATION 1',
                        'STATION 2',
                        'STATION 3'
                    ]
                },
                options: {
                    maintainAspectRatio: false,
                    responsive: true,
                    cutoutPercentage: 87,
                    animation: {
                        animateScale: true,
                        animateRotate: true
                    },
                    legend: {
                        display: false,
                        position: 'bottom',
                        labels: {
                            fontSize: 14,
                            fontFamily: "Poppins,sans-serif"
                        }

                    },
                    tooltips: {
                        titleFontFamily: "Poppins",
                        xPadding: 15,
                        yPadding: 10,
                        caretPadding: 0,
                        bodyFontSize: 16,
                    }
                }
            });
        }
</script>

I haven’t learned about web building but my thesis relates to it. So I really need your support. Please help me.

Display three rows of duplicated data in one row using Javascript Filter()

You can see two data tables in the attached photo.
The first data table shows the same data in all three rows. I don’t need the duplicated datas, so I want to remove the duplicated row of datas and make only one row of data. Please tell me what to do. Everyone Please help me.

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.7/vue.js"></script>
<template>
  <v-container class="container-padding">
    <v-breadcrumbs class="px-0 pt-0" large>
      <span class="breadcrumb-line rounded-pill mr-2"></span>
      <v-breadcrumbs-item class="text-h5 mr-5">Timecard</v-breadcrumbs-item>
      <span class="breadcrumb-divider rounded-pill mr-5"></span>
      <v-breadcrumbs-item class="text-h6">View</v-breadcrumbs-item>
    </v-breadcrumbs>

    <v-card>
      <v-container fluid>
        <v-row>
          <v-col cols="1">
            <v-subheader></v-subheader>
          </v-col>
          <v-col cols="2">
            <v-layout row wrap justify-space-around>
              <v-text-field v-model="calendarVal" label="Date" type="date" value="2022-02-05"></v-text-field>
            </v-layout>
          </v-col>
          <v-col cols="1">
            <v-btn @click="fetchWorkerTimeCard">enter</v-btn>
          </v-col>
        </v-row>
      </v-container>
      <v-data-table v-if="worker_time_card.length > 0"  :headers="headers1" :items="worker_time_card"></v-data-table>
    </v-card>
    <v-card>
      <v-data-table v-if="worker_time_card.length > 0" :headers="headers2" :items="worker_time_card"></v-data-table>
    </v-card>
  </v-container>
</template>
<script>
  export default {
    data() {
      return {
        worker_time_card: [],
        calendarVal: null,
        headers1: [{
            text: 'Start Time',
            value: 'start_time'
          },
          {
            text: 'End time',
            value: 'end_time'
          },
          {
            text: 'Rest time',
            value: 'rest_time'
          },
          {
            text: 'Worked time',
            value: 'worked_time'
          },
        ],
        headers2: [{
            text: 'Project id',
            value: 'project_id'
          },
          {
            text: 'Duration',
            value: 'duration'
          },
          {
            text: 'Work log',
            value: 'work_log'
          }
        ],
      }
    },
    computed: {
      calendarDisp() {
        return this.calendarVal
      },
    },
    mounted() {
      this.calendarVal = this.getDataToday()
      this.fetchWorkerTimeCard()
    },
    methods: {
      getDataToday() {
        return (new Date().toISOString().substr(0, 10))
      },
      submit() {
        console.log(this.calendarVal)
      },
      async fetchWorkerTimeCard() {
        try {
          this.worker_time_card = []
          await this.$axios.$get('/worker_time_card', {
            params: {
              work_date: this.calendarVal
            }
          }).then(data => {
            data.time_cards.forEach(card =>
              this.worker_time_card.push({
                start_time: data.start_time,
                end_time: data.end_time,
                rest_time: data.rest_time,
                worked_time: data.worked_time,
                duration: card.duration,
                work_log: card.work_log,
                project_id: card.project_id,
              })
            )
          })
        } catch (error) {
          console.log(error)
          this.worker_time_card = []
        }
      },
    },
  }
</script>

This project uses the vuetify framework, and the code below is part of the “v-data-table” component. Perhaps if this part is fixed well, it will be possible to make a data table with only one row, but it may be necessary to fix the Javascript part as well.

Javascript how to filter an array using forEach() inside filter()

How to use Next Auth for OTP login?

I’m new to Next Js. Please help me to solve this. I’ve been trying to authenticate my OTP using Next Auth. But I don’t know how to pass the values from component to […nextauth].js

Used signIn property in a function that gets called when I give a right OTP.

  function signInHandler() {
    signIn();
    router.push('/')
  }

My UI where I have the input box and Login Button

  const detail = {
    title: (
      <div style={{ width: "100%" }}>
        <div
          style={{
            display: "flex",
            justifyContent: "space-between",
          }}
        >
          <h3 onClick={callApi}>OTP Verification</h3>
          <div onClick={() => setOtpModal(false)}>X</div>
        </div>
        <div style={{ width: "100%" }}>
          <SmallText style={"text"}>OTP</SmallText>
        </div>
      </div>
    ),
    body: (
      <div style={{ textAlign: "left", width: "100%" }}>
        <div style={{ marginTop: "10px", textAlign: "left", display: "flex" }}>
          <div>
            <SmallText style={styles.stylesheet.text}>
              {validity && " Did not receive OTP ?"}
              {!validity && (
                <div style={{ display: "flex" }}>
                  <div style={{ display: "flex" }}>
                    <Warning /> <div  style={{"margin":"0px 0px 0px 10px"}} >OTP seems to be invalid</div>
                  </div>
                </div>
              )}
            </SmallText>
          </div>
          <div>
            <SmallText style={"glow"}>Resend OTP</SmallText>
          </div>
        </div>

Called the SignInHandler function here to login using “signIn()” in this Button.

        <button style={styles.stylesheet.btnStyle} onClick={signInHandler}>
          Login !
        </button>

My current […nextauth].js

import NextAuth from "next-auth"
import CredentialsProvider from "next-auth/providers/credentials"
import axios from "axios"
import { API_URL } from "./../../../helpers/api/mutations"
import OtpVerification from './../../../components/Components/SignIn/OtpVerification';

This is the place I got stuck. I’m trying to give my API call here with “SignIn” from OTP Verification Component. I want to replace the Email credential to OTP based. Is it possible ?

export default NextAuth({
  providers:[
    Providers.Email({
      // Need the credentials. In my case the OTP to get passed here.
      },
    }),
  ],
  secret: process.env.SECRET,
  session: {
    jwt: true,
  },

Login API call hits when I use signIn(). I first tried with async authorize but it was failed in my case.

  callbacks: {
    jwt: async ({ token, users }) => {
      const user = await axios({
        url: API_URL,
        method: "post",
        data: {
          query: `mutation{
                  login(
                   mobileNumber: "1111111146",
                  mobileCountryCode: "00",
                      password: "admin123"
                ) {
                      expiresAt
                      accessToken
                  }
              }`,
        },
      }).then((result) => {
        console.log(result.data.data,'result')
        return result.data
      })

      token = user.data.login.accessToken

      return user

    },
    session: ({ session, token }) => {
      if (token) {
        session = token
      }

      return session
    },
  },
  theme: {
    colorScheme: "dark",
    brandColor: "",
    logo: "/logo.png",
  },
  debug: process.env.NODE_ENV === "development"
})

React hooks issue when create a drag and drop component

I create a drag and drop component using React hook, with the callback function when drag enters below. If I use the line dragItem.current.itemIndex, 1 instead of currentItemIndex, 1 it is not working. Can somebody tell me why? Thanks!!!
Call back here:

  const handleDragEnter = function handleDragEnter(e, targetItem) {
    if (dragItemNode.current !== e.target) {
      const currentItemIndex = dragItem.current.itemIndex
      setOrder((oldOrder) => {
        let newOrder = JSON.parse(JSON.stringify(oldOrder));
        newOrder.splice(
          targetItem.itemIndex,
          0,
          newOrder.splice(
          //currentItemIndex, 1 // working
          dragItem.current.itemIndex, 1 // not working
          )[0]
        );
        dragItem.current.itemIndex = targetItem.itemIndex
        return newOrder;
      });
    }
  };

Full code here:

function DragNDrop({
  items,
  order,
  setOrder,
}) {

  const [dragging, setDragging] = useState(false);
  const dragItem = useRef();
  const dragItemNode = useRef();

  const handleDragStart = function handleDragStart(e, item) {

    dragItemNode.current = e.target;
    dragItemNode.current.addEventListener("dragend", handleDragEnd);
    dragItem.current = item;

    setTimeout(() => {
      setDragging(true);
    }, 0);
  };

  const handleDragEnter = function handleDragEnter(e, targetItem) {
    if (dragItemNode.current !== e.target) {
      const currentItemIndex = dragItem.current.itemIndex
      setOrder((oldOrder) => {
        let newOrder = JSON.parse(JSON.stringify(oldOrder));
        newOrder.splice(
          targetItem.itemIndex,
          0,
          newOrder.splice(
          //currentItemIndex, 1 // working
          dragItem.current.itemIndex, 1 // not working
          )[0]
        );
        dragItem.current.itemIndex = targetItem.itemIndex
        return newOrder;
      });
    }
  };

  const handleDragEnd = function handleDragEnd(e) {
    dragItem.current = null;
    dragItemNode.current.removeEventListener("dragend", handleDragEnd);
    dragItemNode.current = null;
    setDragging(false);
  };

  const getStyles = (item) => {
    if (dragItem.current.item == item.item) {
      return "dnd-item current";
    }
    return "dnd-item";
  };

  return (
    <div
      style={{
        display: "flex",
        flexDirection: "column",
        alignItems: "center",
        width: "100%",
      }}
      className="drag-n-drop"
    >
      {order.map((item, itemIndex) => (
        <div
          draggable
          key={item}
          onDragStart={(e) => handleDragStart(e, {item, itemIndex})}
          onDragEnter={
            dragging
              ? (e) => {
                  handleDragEnter(e, {item, itemIndex});
                }
              : null
          }
          className={dragging ? getStyles({item, itemIndex}) : "dnd-item"}
        >
          {items[item]}
        </div>
      ))}
    </div>
  );
}

Why does Intellij Code Inspection tell me a selector is never used?

I have this mini-project. It is composed of 2 files in the same folder.

  1. App.css
.App-align-left {
    text-align: left;
}
  1. App.js
import React from 'react';
import 'App.css';

class App extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            data: ''
        }
    }

    render() {
        let contents = <h4>Contents</h4>;
        return (
            <div style={{ display: "inline-block" }}><br />
                <h3 style={{ display: "inline-block" }}>Header</h3>
                <div className="App-align-left">{contents}</div><br />
            </div>)
    }
}

export default App;

When I run code inspection on this, it gives me a warning for App being unused (unused global export), but also for Selector App-align-left is never used. Why is this? It is clearly used.

How to fix the black screen with canvas.toDataURL() on Safari browser?

I have a video player (video.js) in my application, and a function which takes a snapshot of the video.

The function create a canvas which draws the snapshot and convert the canvas into a DataURL.

But this doesn’t work in Safari.

I’m getting a black screen on Safari.

the video tag looks like:

<video crossorigin="anonymous" playsinline="playsinline" id="player_2140_html5_api" class="vjs-tech" data-setup="{ &quot;inactivityTimeout&quot;: 0 }" tabindex="-1" autoplay="autoplay" loop="loop"></video>

This is the function which creates the snapshot:

var canvas = document.createElement('canvas');
canvas.width = 640;
canvas.height = 480;
var ctx = canvas.getContext('2d');
var video = document.querySelector('video');
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
this.snapshotVideo = canvas.toDataURL('image/jpeg', 2.0);

The generated dataUrl in Chrome is an image.
The generated dataUrl in Safari browser is a black rectangle.

In Safari the output is black instead of an image of the taken snapshot via the video, how can I solve this?