Simulate Tab Press Upon Form Submission (React.js+Typescript)

I currently have a list of forms I’m attempting to navigate through, upon the submission of one form – I’d like to simulate a tab keypress (as to progress to the next form). I’m currently using enter as the means of submission, but upon pressing enter – the element I’m manipulating loses focus. The forms are being generated in a for loop, so the use of state to maintain focus seems a bit convoluted. I know this is crude, but is it even possible? Thanks!

const submitHandler = (event: React.FormEvent) => {
    event.preventDefault();
    //Tab KEY PRESS HERE?
    let Result =
      node1.current!.value +
      node2.current!.value +
      node3.current!.value +
      node4.current!.value +
      node5.current!.value;
    console.log(Result.toUpperCase());

    setActive(!true);
  };

  return (
    <form onSubmit={submitHandler}>
      <input
        type="text"
        style={props.success}
        onChange={changeHandler}
        maxLength={1}
        ref={node1}
        disabled={!active}
      />
      <input
        type="text"
        style={props.success}
        onChange={changeHandler}
        maxLength={1}
        ref={node2}
        disabled={!active}
      />
      <input
        type="text"
        style={props.success}
        onChange={changeHandler}
        maxLength={1}
        ref={node3}
        disabled={!active}
      />
      <input
        type="text"
        style={props.success}
        onChange={changeHandler}
        maxLength={1}
        ref={node4}
        disabled={!active}
      />
      <input
        type="text"
        style={props.success}
        onChange={changeHandler}
        maxLength={1}
        ref={node5}
        disabled={!active}
      />
      <input type="submit" style={{ display: "none" }} />
    </form>
  );

Lots of code dupe IK - trying to get this sorted out first!

How to fetch graphQl fragment?

I need to set fragment to my gql. It is working code:

const findEntity = gql`
  query findEntity($pagination: Pagination, $sort: Sort) {
    organizationList(pagination: $pagination, sort: $sort) {
      data {
        _id
        name
      }
    }
  }
`;

This code doesn’t work:

const TEST_FRAGMENT = gql`
  fragment organizationList on OrganizationsPage {
    data {
      _id
      name
    }
  }
`;

const findEntity = gql`
  query findEntity($pagination: Pagination, $sort: Sort) {
    organizationList(pagination: $pagination, sort: $sort) {
      ${TEST_FRAGMENT}
    }
  }
`;

errors: [{message: “Cannot query field “fragment” on type “OrganizationsPage”.”,…},…]

What I do wrong? I think I repeated documentation sample…

Best ways for linking to dynamically generated content?

I’ve researched this topic a bit but unfortunately haven’t come up with many results, and I’m struggling to also word it. I apologize if this has been asked before.

I’m currently working on a university assignment that involves creating a dynamic web application for a video game review website. It’s going pretty well for my first foray into JS and PHP, however, I’ve gotten stuck right at the end. The requirement is that the site needs to use JSON for storing data, and as such, I have a JSON file for the games uploaded to the site. Each game needs to have its own page. I know that I can have a base page for the games, and use JS to grab the data from the server and generate the contents from that.

Is it possible for me to create “dynamic” links to these pages? My idea was to store a variable in the URL, where the variable matches up to an ID for a game, but I’m unsure if this is possible.

Unfortunately I have no code to share that would be of use, and I am unsure of where to begin with this problem.

Thanks.

how to deal with quotations when writing js inside html and vise versa

I got an error

Uncaught SyntaxError: missing ) after argument list

I think the problem with quotations

the code:

<script>var newWindow = window.open();newWindow.document.write('<html><head  onload="'var createtr = document.createElement("tr");  for (m = 0; m < arrayforstu1.length; m++) {createtr.innerHTML='<tr><td style="border-left:none;">'+ arrayforstu1[m][0] +'</td><td style="text-align:right;height:22px"> - <b>' + arrayforstu1[m][1] +'</b></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>'; }document.getElementById("tbod").appendChild(createtr);'"><div id="tbod">aa</div></html>');

How can I use Jest to test these NodeJS Express Functions and Endpoints?

Thank you again for being here. Jr. Developer here, struggling to write my first tests using jest and supertest.

The error I am getting currently is:

ReferenceError: You are trying to import a file after the Jest environment has been torn down. From src/index.test.js.

Here is my jest test file:

const request = require(‘supertest’)
const app = require(‘./index’)

beforeEach(() => {
  jest.useFakeTimers();
});

// // describe("Get /test", () => {
// //   //get swagger documentation
// //   test("should respond with smily face"), async () => {
// //     const response = await (request(app).get("/test"))
// //     expect(response.statusCode).toBe(200)
// //   }
// // })



it('Testing to see if Jest works', () => {
  expect(1).toBe(1)
})

Here is my Index.js

/**
 * Required External Modules
 */

const express = require("express");
const cors = require("cors");
const helmet = require("helmet");
const { clientOrigins, serverPort } = require("./config/env.dev");
const { usersRouter } = require("./users/router.js");
const swaggerJsdoc = require('swagger-jsdoc')
const swaggerUi = require('swagger-ui-express')

/**
* App Variables
*/

const app = express();
const apiRouter = express.Router();

/**
*  App Configuration
*/

app.use(helmet());
app.use(cors({ origin: clientOrigins }));
app.use(express.json());

app.use("/api", apiRouter);

apiRouter.use("/users", usersRouter);

app.use((error, req, res, next) => {
  res.status(error.status || 500).send({
    error: {
      status: error.status || 500,
      message: error.message || 'Internal Server Error',
    },
  });
});

/**
*  Test methods
*/

app.get('/test', (req, res) => {
  res.status(200).send("✋")
})


/**
* Server Activation
*/

app.listen(serverPort, () =>
  console.log(`API Server listening on port ${serverPort}`)
);

/**
 * Swagger
 */

const swaggerOptions = {
  definition: {
    openapi: "3.0.0",
    info: {
      title: "Health Administrator API",
      version: "0.1.0",
      description:
        "This is a simple CRUD API application made with Express and documented with Swagger",
      license: {
        name: "MIT",
        url: "https://spdx.org/licenses/MIT.html",
      },
      contact: {
        name: "Health Dev Team",
        url: "Health",
        email: "faisal@health",
        email: "dave@health",
      },
    },
    servers: [
      {
        url: "http://localhost:6060/",
        description: "Development server"
      },
      
    ],
    
  },
  apis: ["src/users/router.js"],
};

const swaggerSpec = swaggerJsdoc(swaggerOptions);
apiRouter.use('/users-docs', swaggerUi.serve, swaggerUi.setup(swaggerSpec));

module.exports = {
  app
}

Here are some examples from my route.js of code that I would like to test eventually. The problem is.. even the basic test for the simple app.get I wrote is giving me an error :/

let querySQL = (query, res) => {
  try {
    connection.execute(
      query,
      function(err, users, fields) {
        res.status(200).json(users)
      }
    )
  } catch (err) {
    res.json({message:err});
  }
}


addRAHeader = function (req, res, next) {
  let count = 0
  connection.query(getCount, (err, rows) => {
    if(err) throw err
    count =  Object.values(...rows)
    res.header('Access-Control-Expose-Headers', 'Content-Range')
    res.header('Content-Range', `users 0-24/${count[0]}`)
  });
  next()
}


usersRouter.get("/", addRAHeader, checkJwt,  async (req, res) => {
  setTimeout(() => {
    const { sort, range, filter } = req.query
    if (filter || range || sort !== undefined) {
      parsedFilter = JSON.parse(filter).q
      parsedRange = JSON.parse(range)
      lowerRange = parsedRange[0]
      upperRange = parsedRange[1] + 1
      parsedSort = JSON.parse(sort)
      querySQL(queryBuilder(`${parsedSort[0]} ${parsedSort[1]}`, `${parsedRange[0]},${(upperRange - lowerRange)}`, parsedFilter), res)
    } else {
      querySQL(getUsers, res)
    }
  }, 1000)
});

I know it’s quite a long post. I tried to give as much relevant information as possible. Thank you in advance for anyone who might be able to take a look.

EJ2 Data Grid Checkbox Selection

I have an EJ2 data grid code in Javascrpt. I have checkboxes to select 1 to many rows. Upon selecting a row(s), how do I get the “Id” of those rows? Below is my grid definition.

        var grid = new ej.grids.Grid({
            dataSource: @Html.Raw(JsonConvert.SerializeObject((Model), new JavaScriptDateTimeConverter())),
            allowExcelExport: true,
            allowTextWrap: true,
            allowPdfExport: true,
            toolbar: ['ExcelExport', 'PdfExport', 'CsvExport'],
            //editSettings: { allowDeleting: true },
            allowSelection: true,
            allowFiltering: true,
            allowSorting: true,
            allowNumberFormatting: true,
            enableVirtualization: true,
            filterSettings: { type: 'Excel' },
            selectionSettings: { persistSelection: true },
            enableHover: true,
            enableHeaderFocus: true,
            height: 600,
            rowHeight: 38,
            allowPaging: true,
            columns: [
                { type: 'checkbox', width: 10 },
                { field: "Id", visible: false, isPrimaryKey: true},
                { field: "RegistarName",              headerText: "Registrar",         width: 50,},
                { field: "VoterStatus",               headerText: "Voter Status",      width: 50,},
                { field: "strTrainedDate",            headerText: "Trained",           width: 50,},
                { field: "strOathDate",               headerText: "Oath",              width: 50,},
                { field: "Term",                      headerText: "Term",              width: 50,},
                { field: "OrganizationTypeName",      headerText: "Organization Type", width: 50,},
                { field: "RegistrarOrganizationName", headerText: "Organization",      width: 50,},
                {
                    headerText: "",
                    template: "#editTemplate",
                    textAlign: "center",
                    width: 15
                },
                {
                    headerText: "",
                    template: "#deleteTemplate",
                    textAlign: "center",
                    width: 15
                },
            ],
        });

How to reset state using useState? React

I need to reset useState but my code not work.
Check my code

My state ->

  const [selectedUnits, setSelectedUnits] = useState([]);

Function which I get values from dropdown ->

  const handleChange = (value) => {
    setSelectedUnits((prevState) => [prevState, value]); 
    dispatch(
      getSelectedOrganisationUnits({
        selectedOrganisationUnit: [...selectedUnits, value]
      })
    );
  };

handleChange is problem in my code

In next code is function which close dialog and after close dialog clear redux-store ->

 const closeModal = useCallback(() => {
    console.log("on close called");
    setSelectedUnits([]); // TRY TO SET EMPTY USESTATE NO WORK.
    onCancel();
    clearStoreDataAfterCancel();
  }, [onCancel]);

  const clearStoreDataAfterCancel = () => {
    console.log("a");
    setTimeout(() => {
      setSelectedUnits([]); // TRY TO SET EMPTY USESTATE NO WORK.
      dispatch(
        getSelectedOrganisationUnits({
          selectedOrganisationUnit: [] // TRY TO SET EMPTY REDUX STATE WORK!
        })
      );
      dispatch(
        getNewOrganisationUnitName({
          newName: "" // TRY TO SET EMPTY REDUX STATE WORK!
        })
      );
    }, 500);
  };

TO RETURN on problem ->

  const handleChange = (value) => {
    setSelectedUnits((prevState) => [prevState, value]);

    console.log("selectedUnits/", selectedUnits);
    dispatch(
      getSelectedOrganisationUnits({
        selectedOrganisationUnit: [selectedUnits, value]
      })
    );
  };

I will console.log my every change of dropdown items and to show you ->

first dropdown change ->

( console.log value ) : selectedUnits/ []

second dropdown change ->

( console.log value ) : selectedUnits/ 0: [] 1: {label: ‘test’, value:
70}

Third dropdown change ->

(2) [Array(2), {…}] 0: Array(2) 0: [] 1: {label: ‘test’, value: 70}
length: 2 [[Prototype]]: Array(0) 1: label: “test 2” value: 3

Every new time a value is chosen works badly. And what do I want? I just want it to keep my last chosen values.

I have 2 dropdown. Both trigger me to the same function

This is my child component which have a props function handleChange

  <Col>
    <Field 
      component={renderStyledDropdown} 
      options={flatUnits}
      onChange={handleChange} 
    />

    <Field 
      component={renderStyledDropdown} 
      options={flatUnits}
      onChange={handleChange} 
    />
  </Col>

I would very much like to be able to collect these values with 1 function and not make two function for onChange value….

I’ll get back to the problem again.

  const handleChange = (value) => {
    //value is every new selected change.
    
    setSelectedUnits((prevState) => [prevState, value]); 
    dispatch(
      getSelectedOrganisationUnits({
        selectedOrganisationUnit: [...selectedUnits, value]
      })
    );
  };

My desire is to hold previus state and add new state

setSelectedUnits((prevState) => [prevState, value]);

And merged items to set to store

selectedOrganisationUnit: [...selectedUnits, value]

This is no work good.

go back to the console values.

B2C- Unable to hide element with JS in my custom policy

In my custom policy, I try to hide email_intro label but without success :
validateEmail

– This is my html code :

<div id="api" data-name="Unified">
    <form id="attributeVerification">
        <div id="attributeList" class="attr">
            <ul>
                ...
                <li class="TextBox">
                    <div class="attrEntry">
                        <div>
                            <div class="verificationInfoText" id="email_intro" style="display: 
                            inline;" aria-hidden="false" aria-live="polite" 
                            role="alert">Verification is necessary. Please click Send button. 
                        </div>
                    </div>      
                </li>
                ...                             
            </ul>
        </div>
        <div class="buttons">
            ...         
        </div>
    </form>
</div>

– My JS code

var intro = document.getElementById("email_intro");
intro.style.setProperty('display','none');

Could someone know what the error might be please?

PS : I do the same thing to other elements and it works!!

Select only *this* instance of a styled component

I’m designing an input component, with a border on a div wrapping the input, and a label that is a sibling of the input. I want to have the color of the border and the label change when the input is focused.

The problem is: I have two of my component side by side, and when I focus on one, the color of both labels changes! The borders don’t have this problem, by the way, just the labels.


const S = {
  Wrapper: styled.div`
    position: relative;
    border: solid 1px ${theme.colors.lightGrey};

    :hover {
      border-color: ${theme.colors.white};
    }

    :focus-within {
      border-color: ${theme.colors.draftedBlue};
    }
  `,
  Input: styled.input` /* omitted */ `,
  InputLabel: styled.label`
    position: absolute;
    top: -8px;
    left: 8px;

    input:focus + & {
      color: ${theme.colors.draftedBlue};
    }
  `,
};

const SDCurvedInput = ({ ...props }) => (
  <S.Wrapper className={props.className}>
    <S.InputLabel htmlFor={props.label}>{props.label}</S.InputLabel>
    <S.InputWrapper>
      <S.Input {...props} onChange={e => props.onChange(e.target.value)} />
    </S.InputWrapper>
  </S.Wrapper>
);

const Inputs = () => {
  const { entryFee, payout, setEntryFee } = useSlip();

  const clearIfZero = () => {
    if (!parseInt(entryFee)) setEntryFee("");
  };
  const resetToZeroIfBlank = () => {
    if (!entryFee) setEntryFee(0);
  };

  return (
    <S.Wrapper>
      <SDCurvedInput
        label="Entry Fee"
        type="number"
        value={entryFee}
        onChange={v => setEntryFee(parseInt(v))}
        onFocus={clearIfZero}
        onBlur={resetToZeroIfBlank}
      />
      <SDCurvedInput label="Payout" value={payout || 0} readOnly />
    </S.Wrapper>
  );
};

Help!

Why isn’t my second 2 else if statement running?

    Name = window.prompt("Tell your First Name");
    
    
    
    if (Name.endsWith('X') == true || Name.endsWith('x') == true) {
    
        meh = Name.slice(0, -1)
    
        console.log(meh)
    
    } else if (Name.startsWith('X') == true || Name.startsWith('x') == true) {
    
        hello = Name.slice(1)
    
        console.log(hello)
    
    } else if (Name.startsWith('X') == true || Name.startsWith('x') == true && Name.endsWith('X') == true || Name.endsWith('x') == true) {
    
        var result = Name.slice(1) && Name.slice(0, -1);
    
        console.log(result)
    
    } else {
    
        console.log(Name)
    
    }

how can I make my code work with two parameters?

I’m trying to create a signature generator in Java for my project.
I have succeeded with the generator for the full name as a parameter, however, when I try with another method that I want, I fail.

if the firstName is “Izabell Raczynska” then the output I want is izarac01 with a random number between 0 to 20.
else if the input firstName is less than 2 char or Lastname is less than 2 char
I want the output to be izxrax.

This is my code now to make it work but it does not work as I want.



    public String generateSignature(String firstName, String lastName) {
        String[] fName = firstName.split(" ");
        String[] lName = lastName.split("");
        String output = "";
        for (String word : fName) {
            if (word.length() > 3 ) {
                output += word.substring(0, 3);
            } else if (fName.length < 3) {
                output += word.substring(0, 2) + "x";
            }
        }
        for (String word : lName) {
            if (word.length() > 3) {
                output += word.substring(0, 3);
            } else if (lName.length < 3) {
                output += word.substring(0, 2) + "x";
            }
        }
            return output;
    }



This one is the code that works if I pass fullName as an argument. But I want the argument to be first and LastName

static String generateSignature(String fullName) {
        String[] words = fullName.split(" ");
        String output = "";
        for (String word : words) {
            if (word.length() > 3) {
                output += word.substring(0, 3);
            } else if(words.length < 3){
                output += word.substring(0, 2);
            }
        }
        return output;
    }

Facing dynamic routing problem in next.js

So i have this dynamic page in next js

import { useRouter } from 'next/router'
import { WEB_RELATED, PC_EXES } from '../../components/Data';

export default function title() {

    const router = useRouter();
    const { index } = router.query;
    
    console.log(dada.length)
    
    return (
        <div>

        </div>
    )
}

on that dada.length statement i get the error -> dada not defined,
i tried to do the same with index directly but it gave me same problem.
I want to get two strings from the index parameter how do i do that?

How to add an independent function to storybook’s project

I’m starting to integrate storybook to our application, and one of the things I would like to achieve is this:
We have a dark and light theme, which via sass changes a css variables accordingly:

.dark-theme {
  @include theme-colors(true);
}

and: 
@mixin theme-colors($dark-theme) {
  --wc-black-to-white-alpha-7: #{if($dark-theme, $white-alpha-7, $black)};

Normaly, we have a service which responsible of this logic, but the UI component does not inject it by itself.
Now I was wondering if there’s a way to use a function, which is not part of the specific component, to do something like that.
I’ve tried looking at “storybook-dark-mode” (https://storybook.js.org/addons/storybook-dark-mode) which got me the point where I can add a “dark-theme” class to the document of storybook, but not in the app itself (inside the iframe).
Is it possible doing something like this:

import { CommonModule } from '@angular/common';
import { componentWrapperDecorator, Meta, moduleMetadata, Story } from '@storybook/angular';
import { chipStyles } from '@wc/wc-models/src/lib/enums/general';
import { WcChipComponent } from './wc-chip.component';

const styleValues = Object.values(chipStyles);

function toggleDarkTheme() {
 add the .dark-theme class here.
}

export default {
  title: 'wc-chip',
  component: WcChipComponent,
  argTypes: {
    style: {
      options: styleValues,
      control: { type: 'select' },
    },
    _chipClicked: { action: 'clicked' },
  },
 ..........

and use toggleDarkTheme in the story somehow?

REACT – toggle active button class on click

I need 2 buttons, one for the “left” and one for the “right” side. I’ve made a separate component (subfolder) that i am calling in the main file. When the user clicks on certain button it has to become “active”, getting the “square-round–active” class so it shows on the GUI. However currently i am having problem figuring out how to do that on 2 separate buttons, only one of them can be active at the time. In my current code the buttons just switch active from one another when any of them is clicked. How can i solve this ?

    const [isActive, setActive] = useState(false);

    const toggleClass = () => {
        setActive(!isActive);
    };

     <ul class="buttons-in-line no-bullets flex-line">
       <li>
          <button type="button" className={isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
          onClick={toggleClass} >Left</button>
       </li>
       <li>
          <button type="button" className={!isActive ? 'square-round square-round--active square-round--min-width' : 'square-round square-round--min-width'}
          onClick={toggleClass} >Right</button>
       </li>
     </ul>

I am making this as a placeholder for now, but later on i have to adjust the code to work with the backend, sending the users pick (left or right) as boolean value. I am adding the backend code below, if anyone has any idea how to put everything together i would truly appreciate it.

const inoAPI = new konfiguratorreact.client.api.InoAPI();

Getters:
inoAPI.getSestav().getDinId(); // integer

Setters:
inoAPI.getSestav().setDinId(dinId: integer, callback(success, error));