How to implement drag’n’drop for nested lists in React?

I am creating my sidebar component which is divided by sections. What I want to do, is to implement drag’n’drop functionality. But here is the problem, here is how those sections look like in code:

const sidebarSections = [
  {
    name: 'General',
    routePrefix: '/general',
    elements: [
      {
        name: "Home",
        icon: <HomeIcon/>,
        href: "/home",
        show: true
      },
      {
        name: "Clients",
        icon: <SupervisedUserCircleIcon/>,
        href: "/clients",
        show: true
      },
      {
        name: "ACL",
        icon: <ManageAccountsIcon/>,
        href: "/acl",
        show: true
      },
      {
        name: "Modify roles",
        icon: <AddModeratorIcon/>,
        href: "/roles",
        show: true
      },
    ]
  },
...

Every section – in this case General – has its elements. As you probably guess, I want to implement drag’n’drop only for those elements and not for whole sidebarSections.

Here is how this sidebar list looks like in code:

const [sidebar, setSidebar] = React.useState(sidebarSections)

const list = () => (
<Box
  sx={{
    width: anchor === 'top' || anchor === 'bottom' ? 'auto' : 250,
  }}
  role="presentation"
  onKeyDown={toggleDrawer(anchor, false)}
>
  <List>
    {sidebarSections.map((section, key) => (
      <Box
        key={key}
        sx={{
          marginTop: 2,
        }}
      >
        {section.name ? (
          <ListItemText
            sx={{
              px: 2,
              color: 'primary.light',
            }}
          >
            {section.name}
          </ListItemText>
        ) : null}
        <List>
          {section.elements.map((subsection) =>
            subsection.show || settings ? (
              <ListItem key={subsection.name}>
                {settings ? (
                  <Checkbox
                    checked={subsection.show}
                    onChange={() => {
                      subsection.show = !subsection.show;
                      setSidebar((prev) => [...prev]);
                    }}
                  />
                ) : null}
                <Link href={section.routePrefix + subsection.href} passHref>
                  <Button
                    sx={{
                      color: router.pathname.includes(
                        `${section.routePrefix + subsection.href}`
                      )
                        ? "secondary.main"
                        : "primary.main",
                      width: "100%",
                      justifyContent: "start"
                    }}
                    startIcon={subsection.icon}
                  >
                    {subsection.name}
                  </Button>
                </Link>
              </ListItem>
            ) : null
          )}
        </List>
        <Divider
          sx={{color: 'primary.light'}}
        />
      </Box>
    ))}
  </List>
</Box>
)

I was using this guide while was trying to do this, but, because of nested list I wasn’t able to do that.

get keys from the nested array of objects

I am looking for a function that can mutate my data i.e array of object with a nested object. It also shouldn’t include keys that have object/array values (it should only include keys with immediate string/number/boolean values).

Example

[
{
  id: 1,
  person1: {
    firstname: "test1",
    lastname: 'singh',
    address: {
        state: "maharashtra",
    }
  }
},
{
  id: 2,
  person2: {
    firstname: "test2",
    lastname: 'rathod',
    address: {
        state: "kerala",
    }
  }
},
{
  id: 3, 
  person3: {
    firstname: "test3",
    lastname: 'gokale',
    address: {
        state: "Tamilnadu",
    }
  }
}

]

Expected output

[
{
  title: 'person1',
  value: 'person.id'
},
{
    title: 'person1',
    value: 'person.firstname'
},
{
    title: 'person1',
    value: 'person.lastname'
},
{
    title: 'person1',
    value: 'person.address'
},
{
    title: 'person1',
    value: 'person.address.state'
},
...sameforOthers

]

Basically, I need a function that will get an array and will return an array of objects as a given above as expected output

Thanks in advance

Select and update the additional property of NgRx entity using component store

I have the below additional property

export interface MetricCreateState extends EntityState<UserSelectionListDto> {
    isLoading: boolean | undefined,
    isCreated: boolean | undefined,
    LoadConfigureMetric: boolean | undefined
}

Created a adaptor and initial property

export const adapter = createEntityAdapter<UserSelectionListDto>();
export const { selectAll, selectEntities } = adapter.getSelectors();

export const initialState: MetricCreateState = adapter.getInitialState({
    isLoading: false,
    isCreated: false,
    LoadConfigureMetric: false
});

I have a effect which load the data from the server side as

readonly getMetricOwners = this.effect((owners$: Observable<UserSelectionListDtoPagedResultDto>) => {
        this.setState((state) => adapter.setAll([], { ...state, isLoading: true }));
        return owners$.pipe(() => this.userServiceProxy.getUsersForSelection(undefined, undefined, undefined, undefined, undefined).pipe(
            tap({
                next: (owners) => {
                    this.setState((state) => adapter.setAll(owners.items, { ...state, isLoading: false }));
                },
                error: (e) => {
                    this.setIsLoading(false);
                },
            }),
            catchError(() => EMPTY),
        ));
    });

Over here I am trying to update the single property

this.setState((state) => adapter.setAll([], { ...state, isLoading: true }));

Is this is the correct way to set the additional property of the entity? and how do we select the particular additioanl property. For example

  • I want to update only isLoading
  • I want to select only isLoading

why it’s showing ‘myFunc’ is not a function in console? [duplicate]

While using a closure in Javascript as you can see, after running the code I’m facing a error that myFunc is not a function. Can anyone explain me why?

const init = () => {
    const hobby = 'learning javascript'; // Local varibale created  by init function
    const displayHobby = () => { //displayHobby is the inner function, a closure
        console.log(hobby); //Using a variable created in the parent function
    }
    return displayHobby();
}

const myFunc = init();
myFunc();

Functions not executing properly, if statements didn’t work [duplicate]

function OpenMenu(){
 var MenuRotate = getCurrentRotation(document.getElementById("Menu-Icon"));
 var MenuRotate2 = (MenuRotate + MenuRotate2)
document.getElementById("menu").style.margin = "450px";
document.getElementById("Menu-Icon").style.transform ="rotate(90deg)";
var Menu1 = "Open";
alert(MenuRotate);

}
function CloseMenu(){
document.getElementById("menu").style.margin = "-450px";
var Menu1 = "Closed"

}






function Menu() {
    if (Menu1 = "Open") {
    CloseMenu();
    }else{
    OpenMenu2();
    }
    
    
    
} 

function OpenMenu2() {

if (Menu1 = "Closed)"){
 OpenMenu()
    }

}

return

So when I click a picture it executes Menu(), The functions work in the console but don’t work in the script, I’m happy to add further code if needed, the end goal of button is a binary toggle, after 1 click it opens the menu, after 2 it closes the menu and the process can repeat. The issue stemmed from me not being able to have 2 if statements in Menu()

Google Apps Scripts: Confused about how to Update Cards

How do you update the data in PropertiesService and show it in another Card?

The data always seems stale, or the card/UI is stale.

For example…

  1. Set up a project for Google Calendar. Run the buildInitState function to initialize it
// appsscript.json
// set the trigger to build the home
....
....
 "addOns": {
    "calendar": {
      "homepageTrigger": {
        "enabled": true,
        "runFunction": "buildInitState"
      }
    },
    "common": {
      ....
....
  1. Initialize function to build the home card
const userStore = PropertiesService.getUserProperties();

// setup userStore and add default values for date 
userStore.setProperties({
  date: (new Date()).getTime(),
});

const showSettingsPageAction =
  CardService.newAction().setFunctionName('showSettingsPage');

const handleDateChangeAction =
  CardService.newAction().setFunctionName('handleDateChange');

function handleDateChange(e) {
  //change the date to what user selects
  const newDate = (new Date(e.formInput.date_field.msSinceEpoch)).getTime();
  userStore.setProperty('date', newDate);
}

// Homepage card
function buildInitState(e) {
  const mainCard = CardService.newCardBuilder();

  // add a date picker
  const DatePicker = CardService.newDatePicker()
    .setTitle('set date')
    .setFieldName('date_field')
    .setValueInMsSinceEpoch((new Date()).getTime())
    .setOnChangeAction(
      CardService.newAction().setFunctionName('handleDateChangeAction')
    );

  // add a button to nav to another card
  const ButtonFindSlots = CardService.newTextButton()
    .setText('NAV TO SETTINGS CARD')
    .setOnClickAction(showSettingsPageAction);

  mainCard
  .addSection(DatePicker)
  .addSection(ButtonFindSlots)

  mainCard.build();
}
  1. The showSettingsPage builds a new card.
function showSettingsPage() {
  const card = CardService.newCardBuilder();
  const cardSection = CardService.newCardSection();

  let content = userStore.setProperty('date);
  let p = CardService.newTextParagraph().setText(content);

  card.addSection(cardSection);
  return card.build();
}

Even when the user changes the date in the home card and navigates to the settings page, the date always shows the default date value.

I’m not sure if the data ins’t updating or the card is not updating. I’ve tried to read the docs on action responses but I don’t understand it’s suppose to work.

i cant perform auto selected on the select option when data retrieve from the cookie directly after refresh using jquery

This is my code working on getting the cookie data and set into a variable json_str and data retrieve from cookie was fine as refer in this image

But then the jquery statement some how cant be function as expected.

<script>    
        var json_str = getCookie('s8RelatedDepartment');
            const myArray = json_str.split(",");
            if(myArray.includes("volvo")){
                $('select[name=cars] option[value=volvo]').attr('selected','selected');
            }
            if(myArray.includes("opel")){
                $('select[name=cars] option[value=opel]').attr('selected','selected');
            }
            if(myArray.includes("saab")){
                $('select[name=cars] option[value=saab]').attr('selected','selected');
            }
            if(myArray.includes("audi")){
                $('select[name=cars] option[value=audi]').attr('selected','selected');
            }
    </script>
    
    <select name="cars" class="cars" id="cars" style="width:40%" multiple onclick="test()">
        <option value="volvo">volvo</option>
        <option value="opel">Opel</option>
        <option value="saab">Saab</option>
        <option value="audi">Audi</option>
    </select>

The select option will not selected automatically after refresh.
Any ideal?

React with Typescript or Javascript [closed]

Typescript 实际上是 JavaScript 的超集,这意味着在 JavaScript 上运行的任何代码也将能够运行 TypeScript 文件。所有 JavaScript 都是有效的 TypeScript 代码,但并非所有 TypeScript 都是有效的 JavaScript 代码。再读一遍。这个概念类似于所有 CSS 都是有效的 SASS 代码,但并非所有的 SASS 代码都是有效的 CSS 代码。知道了?

如果您熟悉 Typescript 和 React,那么您可以使用以下任一命令运行 React 项目:

npx create-react-app my-app –template typescript

或者

yarn create react-app my-app –template typescript

您正在通过运行以下任一命令将 React JavaScript 项目转换为 TypeScript:

npm install — save typescript @types/node @types/react @types/react-dom @types/jest

或者

yarn add typescript @types/node @types/react @types/react-dom @types/jest

提示:对于那些想将 TypeScript 引入他们的项目但没有精力这样做的人:使用Bit。您可以使用或不使用 TypeScript 创建、组合和发布解耦的 React 组件。这意味着您可以开始将 TypeScript 引入现有的 React 应用程序,一次一个组件!

TypeScript 的优点:

1.易于阅读和理解的组件
2.更好地支持 JSX
3.逐步采用现有项目
4.一般来说,静态类型检查和 IntelliSense 带来的好处
5.更少的未定义错误
6.更好的可读性和可维护性
Javascript 的优点:

1.动态类型
2.不需要编译
3.不使用声明文件
4.非常适合简单的 Web 应用程序
5.快速的重新编译时间
你觉得呢?你有没有什么想法?你更喜欢使用 TypeScript 还是 JavaScript?对于哪些项目,为什么?

mongoose pull specific data from single document

So Im using mongoose and mongo atlas. I have a single document with a structure as follows:

_id: ObjectId("3u3uir3bi2) 
categories : {
   category1: [
    {cat1_item1: "something"},
    {cat1_item2: "something"}
   ],
   category2: [
    {cat2_item1: "something"},
    {cat2_item2: "something"}
   ]
  }

basically I want to use params(?) to only access one category at a time to minimise data sent to the frontend. How do i go about using something like findOne() with the param being either category1 or category2 as I only want the array inside. I am using mongoose, node and express.

Jest failed to parse a file when rendering component using react-testing-library

I’m configuring Jest. When I run nom test, an error shows

Test suite failed to run

    Jest encountered an unexpected token

    Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax.

    Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration.

    By default "node_modules" folder is ignored by transformers.

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it.
     • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript
     • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config.
     • If you need a custom transformation specify a "transform" option in your config.
     • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option.

    You'll find more details and examples of these config options in the docs:
    https://jestjs.io/docs/configuration
    For information about custom transformations, see:
    https://jestjs.io/docs/code-transformation

Details:

    CCCC/chatroom/src/components/SearchBox/SearchBox.test.tsx:11
            SearchBoxComponent = (0, react_1.render)(<index_1.default />);
                                                     ^

    SyntaxError: Unexpected token '<'

SearchBox.tsx

import React from "react";

import IconButton from "@mui/material/IconButton";
import InputBase from "@mui/material/InputBase";
import Paper from "@mui/material/Paper";
import SearchIcon from "@mui/icons-material/Search";

function SearchBox() {
  return (
    <Paper
      component="form"
      sx={{ p: "2px 4px", display: "flex", alignItems: "center", width: 400 }}
    >
      <IconButton sx={{ p: "10px" }} aria-label="search">
        <SearchIcon />
      </IconButton>
      <InputBase
        sx={{ ml: 1, flex: 1 }}
        placeholder="Search or start new chat"
        inputProps={{ "aria-label": "search or start new chat" }}
      />
    </Paper>
  );
}

export default SearchBox;

The test file is below.

SearchBox.test.tsx

import SearchBox from "./index";

import { render, fireEvent, RenderResult } from "@testing-library/react";

let SearchBoxComponent: RenderResult;

describe("SearchBox Component", () => {
  beforeEach(() => {
    SearchBoxComponent = render(<SearchBox />); // the error should be here
  });

  it("checks the placeholder text", () => {
    expect(1).toBe(1);
  });
});

jest.config.ts

export default {
  roots: ["<rootDir>/src"],
  moduleFileExtensions: ["js", "ts", "tsx"],
  moduleDirectories: ["node_modules", "src"],
  moduleNameMapper: {
    "src/(.*)": "<rootDir>/src/$1",
  },
  transform: {
    "^.+\.tsx?$": "ts-jest",
  },
  transformIgnorePatterns: ["<rootDir>/node_modules/"],
};

tsconfig.json

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  },
  "include": ["src"],
  "extends": "./tsconfig.paths.json"
}

tsconfig.paths.json

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "src/*": ["*"]
    }
  }
}

package.json

{
  "name": "my-app",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "@emotion/react": "^11.9.3",
    "@emotion/styled": "^11.9.3",
    "@mui/icons-material": "^5.8.4",
    "@mui/material": "^5.8.5",
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/user-event": "^13.5.0",
    "@types/jest": "^27.5.2",
    "@types/node": "^16.11.41",
    "@types/react": "^18.0.14",
    "@types/react-dom": "^18.0.5",
    "react": "^18.2.0",
    "react-dom": "^18.2.0",
    "react-router-dom": "^6.3.0",
    "react-scripts": "^2.1.3",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "jest",
    "eject": "react-scripts eject"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  },
  "devDependencies": {
    "@babel/preset-typescript": "^7.17.12",
    "@testing-library/react": "^13.3.0",
    "jest": "^28.1.1",
    "ts-jest": "^28.0.5",
    "ts-node": "^10.8.1",
    "typescript": "^4.7.4"
  }
}
```React-testing-library react typescript jest

Javascript DOM methods are not working after Import Class User.js [duplicate]

User.js

export default class User
{
    constructor()
    {
        this.Name;
        this.Email;
    }
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
<body>
    <div>
        <p>Index Page</p>
        <button onclick="AlertFunction()">Click</button>
    </div>
</body>
<script type="text/javascript" src="index.js"></script>
</html>

index.js

import User from './Modules/User.js';

let thisUser = new User();
thisUser.Name = 'Javascript';
console.log(thisUser.Name);

function AlertFunction()
{
    alert('Alert Clicked');
}

Actual problem: AlertFunction() is not working after the import statement. I want to use class User Type in multiple .js files.

I want to write Util class in Javascript and use it for various files inside my project. I am new to Javascript. Before now I was a .net developer.

In .net we can access all .cs (cSharp files) in the environment. We can access it as a new type for the entire project. We don’t need import statements.

But, here in the javascript please help me to understand how import works.

  • How to create a class and use it as a new Type for the entire project. [Pure Javascript]

Redux-Saga fetch the data but is not displaying it on the webpage

I’m learning redux-saga and not sure how why it’s not displaying the data after fetching it. Here is the code:

//actions.js

export const GET_USERS_FETCH = 'GET_USERS_FETCH';
export const GET_USERS_SUCCESS = 'GET_USERS_SUCCESS';

export const getUsersFetch = () => ({
    type: GET_USERS_FETCH
});

//reducer.js
import { GET_USERS_SUCCESS } from "./actions";

const myFirstReducer = (state = {}, action) => {
    switch (action.type) {
        case GET_USERS_SUCCESS: return {...state, users: action.users}
        default: return state
    }
}

export default myFirstReducer;
//sagas.js
import { call, put, takeEvery } from 'redux-saga/effects';

import { GET_USERS_FETCH , GET_USERS_SUCCESS } from './actions';
import axios from 'axios';

function userFetch() {

    axios.get('https://jsonplaceholder.typicode.com/users').then((res) => {
        console.log(res.data);
        return res.data;
    })

}

function* workGetUsersFetch() {

    const users = yield call(userFetch);
    yield put({ type: GET_USERS_SUCCESS, users });

}

function* mySaga() {
    yield takeEvery(GET_USERS_FETCH, workGetUsersFetch);
}

export default mySaga;

Then in index.js I’ve use the @reduxjs/toolkit to configure store as:

//...other code and imports

const sagaMiddleware = createSagaMiddleware();
const rootReducer = combineReducers({ myFirstReducer });
const store = configureStore({ reducer: rootReducer, middleware: [sagaMiddleware] });

sagaMiddleware.run(mySaga);

//...some code

    <Provider store={store}>
      <App />
    </Provider>

//...rest of the code

The webpage I’m calling it from is App.js and here is what I’m doing in that file:

import { useDispatch, useSelector } from 'react-redux';
import { getUsersFetch } from './actions';

function App() {

  const dispatch = useDispatch();
  const users = useSelector(state => state.myFirstReducer.users); //this grabs the users list we have create in our reducer 
  console.log(typeof(users));

  return (
    <div className="App">
      <h1>User</h1><br />
      <button onClick={() => dispatch(getUsersFetch())}>Call API</button>
      <hr />

      <div>
        {users?.map((user => (<div>{user.name}</div>)))}
      </div>
    </div>
  );
}

export default App;

Clicking on the Call API button fetched the data that I can see in the console, but the page remains the same i.e. the .map is not displaying the user.name after the users were fetched. Screenshot below:

enter image description here

So, I’m not sure what I’m missing.

LinkedIn fails to update LIKE button accordingly after each click()

I wrote the following code to automatically ‘LIKE’ all of the comments on a LinkedIn post using a randomized wait time.

The code can find all of the ‘LIKE’ buttons and can click on them however, the page will only update all of the ‘LIKE’ buttons after the full code has been executed

IN SHORT: The page DOES NOT update the ‘LIKE’ button after each click() has been executed.

QUESTION:
I do not know but does the LinkedIn page fail to update after each click() or is my code running all of the click() executing at the same time?

I am trying to avoid all the click() at the same time

// WAIT FUNCTION
function wait(ms){
   var start = new Date().getTime();
   var end = start;
   while(end < start + ms) {
     end = new Date().getTime();
  }
}

// RANDOMIZE WAIT TIME
function randomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// ADD ALL LIKE BUTTONS TO LIST
let likeButtons = document.querySelectorAll('.artdeco-button__text.react-button__text')

// LOOP LIKE ACTION
likeButtons.forEach(likeButton =>{

  // DO CLICK
  console.log("likeButton.click()");
  likeButton.click();

  // ACTIVE WAIT
  var waitTime = randomNumber(1000,4000);
  console.log("wait time is "+ waitTime);
  wait(waitTime);


  }
)

How to Populate HTML page from external page divs content using jquery or js

I have a webpage which will display only the 3 first articles for each section (Politics, economy etc.) in the dedicated grid for each section,
Also the content HTML pages are external (politics.html, economy.html etc)
These external pages are updated by an external app and contains hundreds of articles (divs) as latest is the first on top of page.
So in my index.php page i want to put a grid for each category that displays only the 3 latest articles fro each category, here’s my code for index.php :

<div class="POLSection">
    <div class="Article" id="ArtPOL1>
        <span class="ArticleTitle"></span>
    </div>
    <div class="Article" id="ArtPOL2>
        <span class="ArticleTitle"></span>
    </div>
    <div class="Article" id="ArtPOL3>
        <span class="ArticleTitle"></span>
    </div>
</div>

<div class="ECOSection">
    <div class="Article" id="ArtECO1>
        <span class="ArticleTitle"></span>
    </div>
    <div class="Article" id="ArtECO2>
        <span class="ArticleTitle"></span>
    </div>
    <div class="Article" id="ArtECO3>
        <span class="ArticleTitle"></span>
    </div>
</div>

And this is my code for the external content pages, for example politics.html :

<div id="artpol10">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
<div id="artpol9">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
<div id="artpol8">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
<div id="artpol7">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
<div id="artpol6">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
<div id="artpol5">
    <span class="artPolTitle">Joe Biden to bla bla bla ...</span>
</div>
etc. ..............

in this case i tried to load on index.php grid for politics section lates articles so 10, 9 and 8 to display them when page load …
I tried with jquery.load but the problem is it needs the exact 3 IDs and in my case the IDs latest changes every time the app update the articles page, so it could be 10,9,8 or 11,10,9 or 23,22,21

What the best way to do this if it’s not .load

Is there a way to do this by selecting nth child with jquery or js, so i can choose 1st, 2nd and 3rd child ?

Thanks.