Webrtc screencapture or capturestream

Is there a way to capture on a specific part of the screen.. getting only the element or tag of HTML… I just want to share the video that is playing. I tried to find a solution. I tried the capturestream but the problem is there is no Output on my client-side. Any suggestion or who tried to stream only the video payer on capturestream?

Anyone who successfully broadcast live of the capturestream with broadcaster and client?

Typescript: Function accepting 2 Types but property doesn’t exist on one of the types

I have a function that takes 2 types.

handleDragging(e: CustomEvent<SelectionHandleDragEventType | GridHandleDragEventType>) {
    e.stopPropagation();

    const newValue = this.computeValuesFromPosition(e.detail.x, e.detail.y, e.detail.variant);

    // other same code
})

the issue is that GridHandleDragEventType does not have a variant as part of the type. In those cases, I don’t mind sending null but I keep getting the TS issue:
Property 'variant' does not exist on type 'GridHandleDragEventType'. Is there a clean way to resolve this?

Eclipse is weird

enter image description here

Here, in this image, I have inserted the value of ‘int’ (number)variable=22, and in the braces beside ‘while’, I have entered (number < 20) and I have asked to print ‘alright’, and even the condition is not true here, the eclipse is printing ‘alright’!!

Highlighting text in Safari on iPad

I am developing an application that allows user to highlight text in a web app. With iOS on iPad many users would like to use their Apple Pencil to highlight text. While it is of course possible to highlight text by double tapping or holding the pencil down, I would like to enable users to activate a mode in which they can just brush over the text to highlight it.

Is there an API in Safari for iOS that enables such behaviour?

How to populate modal form inputs properly onto FullCalendar in javascript?

I am coming to an issue where I am trying to place the form details onto the calendar but I am stuck on this area. For testing purposes when I click on submit I am alerting the form details in that view. However, I just want it to be place on the calendar, similar to Google Calendar. Thank you for the help.
PS: Let me know if you want to see the html form as well.

here is my code:

Javascript:

    document.addEventListener('DOMContentLoaded', function() {
    var calendarEl = document.getElementById('calendar');
    var myModal = new bootstrap.Modal(document.getElementById('schedule-edit'), {});
    var calendar = new FullCalendar.Calendar(calendarEl, {
        selectable: true,
        initialView: 'dayGridMonth',
        select: function(info, start, end, jsEvent) {
            myModal.show();
                if (info) {
               calendar.addEvent({
               title: title,
               start: info.startStr,
               end: info.endStr
               })
            calendar.unselect();
        },
    });
    calendar.render();
});

 function submitForm() {

        let title = document.getElementById("title").value || "";
        let project = document.getElementById("project").value || "";
        let time = document.getElementById("time").value || "";
        let timeSpent = document.getElementById("timeSpent").value || "";
        let description = document.getElementById("description").value || "";
        let editorS = document.getElementById("sampleeditor").value || "";
        let firstList = document.getElementById("firstList").value || "";
        let startDate = document.getElementById("myDate").value || "";
        let dueDate = document.getElementById("myDue").value || "";



        //for test only
       alert(title + project + time + timeSpent + description + editorS + firstList + startDate + dueDate);


    }

How can i display all the data from a data table in the Pie Chart.js?

I have this task where i have to display all the data from the table which i will provide it with an image, but i can only display the data that are shown in the data table when the pagination is: false. I need to display all the data when the pagination is: true.
This is the image display

<input class="form-control-xs" type="date" id="start" onchange="table.column(3).search(this.value).draw();">

<script>
'use strict'
let url='{{ $objApi }}';
let columnDef=[
    {"title":"ID","data":"0"},
    {"title":"Method","data":"1"},
    {"title":"Path","data":"2"},
    {"title":"Date","data":"3"},
    {"title":"Counter","data":"4"}
];

let table=$('#adminuser').DataTable({
    columns: columnDef,
    processing: true,
    serverSide: true,
    paging: true,
    ajax: {
        'url': url,
        'method': 'GET'
    },
    "searchCols": [
        null,
        null,
        null,
        {"search": currentDate},
        null
    ],
    "order": [[4, 'desc']],
    language: {
        searchPlaceholder: 'Search...',
        sSearch: '',
        lengthMenu: '_MENU_ items/page',
    },
});
</script>
 var ctx = document.getElementById("canvas").getContext("2d");
const data = {
                labels: [],


                datasets: [{
                    label: 'Counter',
                    data: [],
                    backgroundColor: [
                        'rgba(90, 57, 228, 0.7)',
                        'rgba(84, 73, 44, 1)',
                        'rgba(143, 105, 20, 0.1)',
                        'rgba(74, 3, 153, 0.1)',
                        'rgba(81, 35, 162, 0.6)'
                    ]
                }]
            }; 

let mychart = new Chart(ctx, {  type: 'pie', data: data, options: {plugins: {legend: {display: false}}},});

table.on( 'draw', function () 
{
    rows=table.rows().data().toArray();
    console.log(rows);
    let labels=[];
    let data=[];
    rows.forEach((element) => {
        labels.push(element[2] + ' ' + element[1]);
        data.push(element[4]);
    });
    mychart.data.labels = labels;
    mychart.data.datasets[0].data = data; // or you can iterate for multiple datasets
    mychart.update(); // finally update our chart
} );

How to add class name equal to the key to th in table on Ant Design Vue 3?

I need to add a class name to the th accordingly to the :key attribute in Vue 3 for some styles that I’m doing. I’m not sure how to do it and I was wondering if it’s possible to do it straight on the template. Can you guys help me?

This is my code:

<template>
     <a-table bordered :data-source="tableData.data" :columns="tableData.columns" :pagination="false" class="tableEditable">
        <template v-for="col in this.editableCells" #[col]="{ column, text, record }" :key="col">
            <div class="editable-cell">
                <div v-if="editableData[record.key + '|' + column.key] !== undefined" class="editable-cell-input-wrapper">
                    <a-input v-model:value="editableData[record.key + '|' + column.key]" @pressEnter="save(record.key, column.key)" type="number" />
                    <check-outlined class="editable-cell-icon-check" @click="this.save(record.key, column.key)" />
                </div>
                <div v-else class="editable-cell-text-wrapper">
                    {{ text || ' ' }}
                    <edit-outlined class="editable-cell-icon" @click="this.edit(record.key, column.key)" />
                </div>
            </div>
        </template>
        <template #buttonTable="{text, record}">
            <div class="editableTableButtonOption">
                {{text}}
                <Popper arrow :locked="true">
                    <button class="statusButtonCrud synch" v-if="showEditableButton(record.key)"> {{this.buttonText}} </button>
                    <template #content="{close}">
                        <div class="popperOptions">
                            <li v-for="options in this.optionsToEdit" :key="options" class="popperOptionsList" v-on:click="this.emitOption(options.method), close();">
                                {{$filters.translate(options.title)}}
                            </li>
                        </div>
                    </template>
                </Popper>
            </div>
        </template>
    </a-table>
</template>
<script>

import { CheckOutlined, EditOutlined } from '@ant-design/icons-vue';

export default {
    name: 'TableEditable',
    props: {
        editableCells: Array,
        tableData: Object,
        buttonText: String,
        optionsToEdit: Array
    },
    emits: ['change', 'editRow', 'editColumn', 'editAllCells'],
    components: {
        CheckOutlined,
        EditOutlined
    },
    data(){
        return {
            editableData: {},
            selectedRow: '',
            selectedColumn: '',
            valueSaved: ''
        }
    },
    methods: {
        edit(row, column) {
            this.editableData[row + '|' + column] = this.tableData.data.filter((item) => row === item.key)[0][column];
        },
        save(row, column) {
            let data = {...this.tableData.data};
            if (this.editableData[row + '|' + column] == '') {
                data[row][column] = '0'
            } else {
                data[row][column] = this.editableData[row + '|' + column];
                this.valueSaved = data[row][column]
            }
            delete this.editableData[row + '|' + column];
            this.selectedRow = row;
            this.selectedColumn = column;
            this.$emit('change', data);
        },
        showEditableButton(row) {
            if (this.selectedRow == row) {
                return true
            }
        },
        emitOption(method) {
            this.$emit(method, this.selectedRow, this.selectedColumn, this.valueSaved);
        },
    },
}
</script>
<style>

Thanks in advance. If this question is not clear enough please let me know so I can edit it.

How can add properties to my objects based on the duplicates inside the array?

I have this array of objects

let arr = [
    {
        id: 1,
    },
    {
        id: 1,
    },
    {
        id: 2,
    },
    {
        id: 1,
    },
    {
        id:4,
    },
    {
        id: 3,
    },
    {
        id:4,
    }
]

i need to find and change every object in the array based on condition.
So if there are duplicates in the array i need to set on my objects 100 except last duplicate where i should have 200.
If i don’t have any duplicates than i should have again 200

So the output shpuld be

let arr = [
    {
        id: 1,
        number: 100
    },
    {
        id: 1,
        number: 100
    },
    {
        id: 2,
        number: 200
    },
    {
        id: 1,
        number: 200
    },
    {
        id:4,
        number: 100
    },
    {
        id: 3,
        number: 200
    },
    {
        id:4,
        number: 200
    }
]

so id 1 has duplicates.
That is why the fiurst occurences are set with number:100 and the last one i set with number:200.

Id 2 has number 200 because there are no duplicates and it is first occurance in the list.

what i tried

I got stuck at

for(let item of arr) {
    for(let item2 of arr) {
        if(item.id === item2.id) {
            item.number = 100;
        } else {
            item.number = 200;
        }
    }
}

Find minimum group of array with difference less than k

I am working on code where I need to find the count of array group with difference between the elements of the array group should be less than k

Example
The numbers of awards per movie are awards = [1, 5, 4, 6, 8, 9, 2],
and the maximum allowed difference is k = 3.

  • One way to divide the movies into the minimum number of groups is:
    The first group can contain [2, 1]. The maximum difference between
    awards of any two movies is 1 which does not exceed k.

  • The second group can contain [5, 4, 6]. The maximum difference between awards of
    any two movies is 2 which does not exceed k

  • The third group can
    contain [8, 9]. The maximum difference between awards of any two
    movies is 1 which does not exceed k. The movies can be divided into
    a minimum of 3 groups.

below is my code
But it is not working. What I am doinng wrong. Please help me.

function minimumGroups(nums, k) {
    // Write your code here
nums.sort((a,b) => (a - b))
    let result = 0
    for(let i = 0; i < nums.length; i++){
        if(i > 0 && nums[i] === nums[i - 1])
            continue
        for(let j = i + 1; j < nums.length; j++){
            let diff = nums[j] - nums[i]
            if(diff === k){
                result += 1
                break
            }
            if(diff > k) break
        }
    }
    return result
}

Sorting an .env file while preserving comments and empty lines

While trying to sort an .env file, I’m wondering what’s the most performant way of doing it while also preserving empty lines and (single or multiple) comments.

APP_URL=https://awesome-app.io
APP_NAME=testing
APP_ENV=prod
APP_KEY=
APP_DEBUG=
# this is a comment
# another comment
# third comment
PORT=

DB_CONNECTION=
DB_HOST=
DB_PORT=
DB_DATABASE=
DB_USERNAME=scott
DB_PASSWORD=tiger

test4="key#a23" # with comment
OTHER_ENV=

Ideally this should be sorted as this –

APP_DEBUG=
APP_ENV=prod
APP_KEY=
APP_NAME=testing
APP_URL=https://awesome-app.io

DB_CONNECTION=
DB_DATABASE=
DB_HOST=
DB_PASSWORD=tiger
DB_PORT=
DB_USERNAME=scott
LOG_CHANNEL=
OTHER_ENV=
# this is a comment
# another comment
# third comment
PORT=

test4="key#a23" # with comment

Convert key/value array

What is the best way to convert to following array. Do I need to map over it or is there some other way with Object.values etc:

[
  {
    key: "eyeColor",
    value: "Blue/Green",
   },
   {
     key: "eyeColor",
     value: "Blue",
   },
   {
     key: "hairColor",
     value: "black",
   }
];

into:

[
  {
    eyeColor: ["Blue/Green", "Blue"]
  },
  {
    hairColor: ["black"]
  },
];

DSpace 7.1, Bulk import failed

I am not able to import updated metadata file after i have exported from DSpace. Please find the below mentioned error list and we are using DSpace Version 7.1.

2022-02-25 09:27:58.603 INFO metadata-import – 48 @ The script has started
2022-02-25 09:27:58.831 ERROR metadata-import – 48 @ null
2022-02-25 09:27:58.831 ERROR metadata-import – 48 @ java.lang.NullPointerException
at org.dspace.app.bulkedit.MetadataImport.contains(MetadataImport.java:1183)
at org.dspace.app.bulkedit.MetadataImport.compareAndUpdate(MetadataImport.java:721)
at org.dspace.app.bulkedit.MetadataImport.runImport(MetadataImport.java:415)
at org.dspace.app.bulkedit.MetadataImport.internalRun(MetadataImport.java:217)
at org.dspace.scripts.DSpaceRunnable.run(DSpaceRunnable.java:104)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:834)

Specify size limit of the items going to be set in cache in nestjs In-memory cache

Is there any option to set the maxSize(in bytes) of the cache or the size limit for the items going to be stored in the in memory cache in nestjs .

My current implementation looks like :

//app module

CacheModule.register({
      max: 100,
      isGlobal: true
    })

// usage 

this.client.set(userId, inputId, { ttl: 600})

I checked the function signature and there were no options available .

RTK Query set token inside cookies but it is not having any effect

I started learning RTK Query few days ago and I have been enjoying it cool features and simplicity, so I decided to switch from useContext to RTK Query in the project I’m building with Next.js and a custom server using Node.js and express. In this project, I made an api route for login and signup which would be hit by using RTK Query and Axios with the help of custom axios base query RTK Query provided. The login and signup api endpoints already had a logic to store token inside the cookies storage. I use RTK Query with axios to post user request so they can get a response of their token store in cookies storage. This logic of storing user token in the cookies works well with useContext and axios.
But the logic didnot work as expected while using RTK Query, and these are results:

  • The token was set in the cookies storage but I get a response status of 401.
  • When user submit their credentials in the login or signup page, they are supposed to be redirected to profile page with their details being display since I made use of useQuery to fetch user profile. But the data did not display. Which means the token stored is not effective.
  • I’m unable to get the user information even though the token had been stored in the cookies.
  • Whenever I click on a link to redirect me to a particular route, useQuery didnot fetch anything and when I go back to profile, the user details will be fetched and display but when I refresh the page again, no data will be dsiplay
  • Whenever a get request was successful at the first time, I alway lose the data whenever I refresh the page.
  • All these issues only happens to routes that are protected with middleware in the backend and the middleware is to verify the token. But I have no issue with reloading a page which data that is not protected in the backend.
  • I also have a middleware in my backend for verifying and checking if token is true in the cookie to check if user is authenticated, if it is false, user should be directed to the login page in the frontend. The logic for fetching and check if data is true is inside HOC component which was wrapped with protected route, but whenever the data value is false, am still able to go to any route in the frontend instead of redirecting me to login page. And when I log the data to the console I recieve the correct data.
  • Removing token from cookie works successfully.

Note: Backend code isrunning fine as it was tested with thunder client and everything works fine when using it with useContext.
Here is my login api route.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const router = require("express").Router();
const { body, validationResult } = require("express-validator");
const User = require("../../Model/UserSchema");
const jwt = require("jsonwebtoken");
const bcrypt = require("bcryptjs");

router.post(
  "/login",
  [
    body("email", "Email is required").isEmail(),
    body("password", "At least 6 characters").exists(),
  ],
  async (req, res) => {
    const errors = validationResult(req);

    if (!errors.isEmpty()) {
      return res.status(400).json({ errors: errors.array() });
    }

    const { email, password } = req.body;
    try {
      const existingUser = await User.findOne({ email });

      if (!existingUser)
        return res
          .status(401)
          .json({ errors: [{ msg: "Wrong email or password" }] });

      const passwordCorrect = await bcrypt.compare(
        password,
        existingUser.password
      );

      if (!passwordCorrect) {
        return res.status(401).json({ msg: "Wrong email or password" });
      }

      const token = jwt.sign(
        { user: existingUser._id },
        process.env.JWT_SECRET
      );

      //send cookies in httpOnly

      res.cookie("token", token, {
        httpOnly: true,
        sameSite: "strict",
      }).send;
      res.status(200).send("Login Successful");
    } catch (err) {
      res.status(400).json("Bad Request");
    }
  }
);

module.exports = router;

The register api route is similar with the login route.

Here is the code for my middleware for storing cookies with user id

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const jwt = require("jsonwebtoken");

function auth(req, res, next) {
  try {
    const token = req.cookies.token;

    if (!token) {
      return res.status(401).json({ msg: "Unauthorized" });
    }

    const verified = jwt.verify(token, process.env.JWT_SECRET);

    req.user = verified.user;

    next();
  } catch (err) {
    console.log(err);
    res.status(401).res.json({ msg: Unauthorized });
  }
}

<!-- begin snippet: js hide: false console: true babel: false -->
module.exports = auth;

Here is the middleware for checking if token is true in cookies

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

const jwt = require("jsonwebtoken");
const router = require("express").Router();

router.get("/auth", (req, res) => {
  try {
    const token = req.cookies.token;

    if (!token) {
      return res.json(false);
    }
    jwt.verify(token, process.env.JWT_SECRET);

    res.send(true);
  } catch (err) {
    res.json(false);
  }
});

module.exports = router;

Here is my AxiosBaseQuery and createApi

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import axios from "axios";
import { createApi } from "@reduxjs/toolkit/query/react";


const axiosBaseQuery =
  ({ baseUrl } = { baseUrl: "" }) =>
  async ({ url, method, data }) => {
    try {
      const result = await axios({ url: baseUrl + url, method, data });
      return { data: result.data };
    } catch (axiosError) {
      let err = axiosError;
      return {
        error: { status: err.response?.status, data: err.response?.data },
      };
    }
  };


export const fetcherApi = createApi({
  reducerPath: "fetcherApi",
  baseQuery: axiosBaseQuery({
    baseUrl: "http://localhost:5000/",
  }),
  tagTypes: ["User"],
  endpoints(build) {
    return {
      //________Authentication
      registerUser: build.mutation({
        query: (form) => ({
          url: "register",
          method: "post",
          data: form,
        }),
        invalidatesTags: ["User"],
      }),

      loginUser: build.mutation({
        query: (form) => ({
          url: "login",
          method: "post",
          data: form,
        }),
        invalidatesTags: ["User"],
      }),

      getAuth: build.query({
        query: () => ({ url: "auth", method: "get" }),
      }),

      //__________User
      updateUserName: build.mutation({
        query: (...rest) => ({
          url: "update-user",
          method: "put",
          data: rest,
        }),
        invalidatesTags: ["User"],
      }),

      getUser: build.query({
        query: () => ({ url: "user", method: "get" }),
        providesTags: ["User"],
      }),

      //__________Profile
      postProfile: build.mutation({
        query: (form) => ({
          url: "login",
          method: "post",
          data: form,
        }),
      }),

      getAllProfiles: build.query({
        query: () => ({ url: "all-profiles", method: "get" }),
      }),

      getUserProfile: build.query({
        query: () => ({ url: "profile/me", method: "get" }),
      }),

      //___________Car
      postCar: build.mutation({
        query: (form) => ({
          url: "new-car",
          method: "post",
          data: form,
        }),
      }),

      putCar: build.mutation({
        query: ({ id, ...rest }) => ({
          url: `update-car/{id}`,
          method: "put",
          data: { rest },
        }),
      }),

      getAllCars: build.query({
        query: () => ({ url: "all-cars", method: "get" }),
      }),

      getCarById: build.query({
        query: (id) => ({ url: `onecar/${id}`, method: "get" }),
      }),

      getAllUserCars: build.query({
        query: () => ({ url: "my-car", method: "get" }),
      }),
    };
  },
});

export const {
  // ______Authentication______
  useGetAuthQuery,
  useRegisterUserMutation,
  useLoginUserMutation,
  //_______User_________
  useUpdateUserNameMutation,
  useGetUserQuery,
  //_____Profile_________
  useGetUserProfileQuery,
  useGetAllProfilesQuery,
  usePostProfileMutation,
  //_____Car____________
  usePostCarMutation,
  usePutCarMutation,
  useGetAllCarsQuery,
  useGetCarByIdQuery,
  useGetAllUserCarsQuery,
} = fetcherApi;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import Layout from "@/components/Layout";
import Image from "next/image";
import { FaDollarSign } from "react-icons/fa";
import Link from "next/link";
import { FiEdit } from "react-icons/fi";
import Authorization from "@/HOC/Authorization";
import {
  useGetUserProfileQuery,
  useGetUserQuery,
} from "@/store/ReduxStore/fetcherApi";
import MyCars from "@/components/MyCars";

function Profile() {
  const { data: profileData } = useGetUserProfileQuery();
  const { data: userData } = useGetUserQuery();

  return (
    <Layout>
      <div className="flex items-center justify-center mt-8 mx-auto w-4/5 ">
        {/* Card code block start */}
        <div className="bg-gray-300 shadow rounded-lg">
          <div className="relative ">
            <button className="w-full">
              <div className="coverpicstwo">
                <p className="text-xs text-gray-100">Change Cover Photo</p>
                <div className="ml-2 text-gray-100">
                  <FiEdit />
                </div>
              </div>
              <Image
                className="h-1/6 shadow rounded-t w-full object-cover object-center"
                src="/assets/images/d17.jpg"
                alt="profile"
                width={10000}
                height={2000}
              />
            </button>
            <button className="roundedprofile">
              <Image
                className="w-full h-full z-10 overflow-hidden object-cover rounded-full"
                src="/assets/images/d17.jpg"
                alt="profile-image"
                layout="fill"
              />
            </button>
          </div>
          <div className="px-5 xl:px-10 pb-10 mt-2">
            <div className="flex justify-center xl:justify-end w-full pt-16 xl:pt-5"></div>
            <div className="pt-3 xl:pt-5 flex flex-col xl:flex-row items-start xl:items-center justify-between">
              <div className="xl:pr-16 w-full xl:w-2/ mb-6 ">
                <div className="profileidentity">
                  <h2 className="profilename">{userData?.name}</h2>
                  <div className="profilestatus">
                    {profileData ? (
                      <p>{profileData.businessStatus}</p>
                    ) : (
                      <p>Buyer</p>
                    )}
                  </div>
                </div>
                <div className="profiledescription ">
                  {profileData ? (
                    <p>{profileData.description}</p>
                  ) : (
                    <p>Setup description</p>
                  )}
                </div>
              </div>

              <div className="workingstatusone">
                <div className="workingstatustwo">
                  <Link href="/new-car" passHref>
                    <button className="workingstatusthree">
                      <span>
                        <FaDollarSign className="text-xl mr-1" />
                      </span>
                      Sell
                    </button>
                  </Link>
                  <div className="availablestatus">
                    {profileData ? (
                      <p>{profileData.availability}</p>
                    ) : (
                      <p>Available</p>
                    )}
                  </div>
                </div>
                <div className="profilecontactbutton">
                  <Link
                    href="/profile-setup"
                    onClick={() => {
                      userNameHandler();
                      profileHandler();
                    }}
                    passHref
                  >
                    Contact || Edit Profile
                  </Link>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <MyCars />
    </Layout>
  );
}
export default Authorization(Profile);

Here is where profile can be edited. I made the previous profile as the current value, whenever the page is refresh the value will be lost.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import Layout from "@/components/Layout";
import Authorization from "@/HOC/Authorization";
import {
  useGetUserProfileQuery,
  useGetUserQuery,
  useUpdateUserNameMutation,
} from "@/store/ReduxStore/fetcherApi";
import { useState, useEffect } from "react";
import Image from "next/image";
import { FiEdit } from "react-icons/fi";
import PhoneInput from "react-phone-input-2";
import { useRouter } from "next/router";
import { usePostProfileMutation } from "@/store/ReduxStore/fetcherApi";
import Link from "next/link";

const ProfileSetup = () => {
  const router = useRouter();
  const [postProfile] = usePostProfileMutation();
  const [updateUserName] = useUpdateUserNameMutation();
  const { data: profile } = useGetUserProfileQuery();
  const { data: user } = useGetUserQuery();

  const [name, setName] = useState(user?.name);
  const [description, setDescription] = useState(profile?.description);
  const [businessStatus, setBusinessStatus] = useState(profile?.businessStatus);
  const [availability, setAvailability] = useState(profile?.availability);
  const [phoneNumber, setPhoneNumber] = useState(profile?.phoneNumber);

  const form = {
    description,
    businessStatus,
    availability,
    phoneNumber,
  };
  const submitProfile = async (e) => {
    e.preventDefault();
    updateUserName(name);
    postProfile(form);
    router.push("/profile");
  };

  return (
    <Layout>
      <form onSubmit={submitProfile}>
        <div className="bg-gray-100 ">
          <div className="profilesetupheader">
            <div className="profilesetupline">
              <div className="flex w-11/12 mx-auto xl:w-full xl:mx-4 items-center">
                <p className="setupheadertext">Profile Setup</p>
              </div>
            </div>
            <div className="mx-auto">
              <div className="xl:w-9/12 w-11/12 mx-auto xl:ml-8">
                <div className="rounded relative mt-8 h-48">
                  <div className="coverpicsone" />
                  <div className="coverpicstwo">
                    <p className="text-xs text-gray-100">Change Cover Photo</p>
                    <div className="ml-2 text-gray-100">
                      <FiEdit />
                    </div>
                  </div>
                  <input
                    className="backgroundprofile"
                    type="file"
                    name="myImage"
                    accept="image/png, image/gif, image/jpeg"
                    // onChange={profileImageBackgroundUpload}
                  />
                  <button className="profilepics">
                    <Image
                      src="/assets/images/d17.jpg"
                      alt="myprof"
                      className=" rounded-full"
                      layout="fill"
                    />
                    <div className="profilepicsoverlay" />
                    <div className="cursor-pointer flex flex-col justify-center items-center z-10 text-gray-100">
                      <FiEdit />
                      <p className="text-xs text-gray-100">Edit Picture</p>
                    </div>
                    <input
                      className="profileimage"
                      type="file"
                      name="myImage"
                      accept="image/png, image/gif, image/jpeg, image/jpg"
                    />
                  </button>
                </div>
                <div className="mt-16 flex flex-col xl:w-2/6 lg:w-1/2 md:w-1/2 w-full">
                  <label htmlFor="name" className="mylabel">
                    Name
                  </label>
                  <input
                    type="text"
                    name="name"
                    className="formname"
                    placeholder="John Doe"
                    onChange={(e) => setName(e.target.value)}
                    value={name}
                    required
                  />
                </div>
                <div className="mt-8 flex flex-col xl:w-3/5 lg:w-1/2 md:w-1/2 w-full">
                  <label htmlFor="description" className="mylabel">
                    Description
                  </label>
                  <textarea
                    type="text"
                    name="description"
                    className="formdescription"
                    placeholder="Let the world know who you are"
                    onChange={(e) => setDescription(e.target.value)}
                    value={description}
                    maxLength="400"
                    required
                  />
                </div>
              </div>
              <div className="ml-10">
                <div className="inline-flex justify-between py-4  space-x-20 ">
                  <div className=" flex flex-col xl:w-2/6 lg:w-1/2 md:w-1/2 w-full">
                    <label htmlFor="Buyer" className="mylabel">
                      Business Status
                    </label>
                    <select
                      name="businessStatus"
                      onChange={(e) => setBusinessStatus(e.target.value)}
                      value={businessStatus}
                      className="bg-gray-200 p-2"
                    >
                      <option>* Select Business Status</option>
                      <option value="buyer">Buyer</option>
                      <option value="seller">Seller</option>
                    </select>
                  </div>
                </div>
                <p className="mylabel">Available</p>
                <select
                  name="availability"
                  value={availability}
                  onChange={(e) => setAvailability(e.target.value)}
                  className="bg-gray-200 p-2 "
                >
                  <option>* Select Availability </option>
                  <option value="yes">Available</option>
                  <option value="no">Unavailable</option>
                </select>
                <div className="mt-6 mb-8 flex flex-col xl:w-2/6 lg:w-1/2 md:w-1/2 w-full pr-8">
                  <label htmlFor="phoneNumber" className="mylabel">
                    Phone Number
                  </label>
                  <PhoneInput
                    country={"us"}
                    name="phoneNumber"
                    onChange={phoneNumberChange}
                    value={phoneNumber}
                  />
                  <p className="w-full text-left text-xs pt-1 text-gray-500 ">
                    You might choose not to include your phone number if this
                    seems like a security concern.
                  </p>
                </div>
              </div>
            </div>
            <div className="ml-10 justify-end">
              <Link href="/profile" passHref>
                <button className="profilecancelbutton">Cancel</button>
              </Link>
              <button
                className="profilesubmitbutton"
                type="submit"
                onClick={submitProfile}
              >
                Save
              </button>
            </div>
          </div>
        </div>
      </form>
    </Layout>
  );
};

export default Authorization(ProfileSetup);

Here is my HOC component for redirecting users that are not authenticated.

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import axios from "axios";
import { useGetAuthQuery } from "@/store/ReduxStore/fetcherApi";
import { setHttpAgentOptions } from "next/dist/server/config";

export default (ChildComponent) => {
  const composeComponent = (props) => {
    const router = useRouter();

    const { data: authData } = useGetAuthQuery();
    const [page, setPage] = useState(undefined);

    useEffect(() => {
      if (authData && authData === false) {
        router.push("/login");
      } else {
        setPage(<ChildComponent {...props} />);
      }
    }, []);

    return <div>{page}</div>;
  };
  return composeComponent;
};

How do I use data from an API using JSON parse

I am trying to get data by using JSON and use that data in a chart.
This is what i get from JSON

{ got json response {"id": 8900.937201864273, "jsonrpc": "2.0", "result": [{"__domain": [Array], "date:day": "07 Dec 2021", "date_count": 1, "unit_amount": 4}, {"__domain": [Array], "date:day": "08 Dec 2021", "date_count": 4, "unit_amount": 7.5}]} }

I need to put the exact dates i get as labels and unit_amount as data for the chart and I don’t know how to use parse.

const res = await countRecords();
const parseRes = JSON.parse(res);
console.log("res: ", parseRes)

If I try to console log parseRes.unit_amount I get the same result. Can anyone help me please. Thank you in advance.