Is there a way to adjust user privileges within a MenuItem?

One of my tasks is to set a default value based on the previous selection in the Userlevel dropdown. The value will be determined by the Username selected, and I need to dynamically update the default value label accordingly. For example, if "dev_sams" is selected in the Username dropdown, then the maker should automatically be set to true. To better understand how the values and labels are updated, you can refer to the provided CodeSand Box link.

import React, { useMemo } from "react";
import {
  Grid,
  Card,
  CardContent,
  Button,
  Box,
  TextField,
  MenuItem,
  makeStyles
} from "@material-ui/core";
import { useFormik } from "formik";
const useStyles = makeStyles((theme) => ({
  formGrid: {
    padding: theme.spacing(2)
  },
  tableContainer: {
    maxHeight: 440
  }
}));
const userList = [
  {
    username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5b3a3a39383f1b3e363a323775383436">[email protected]</a>",
    maker: true,
    checker1: false,
    checker2: false,
    checker3: false,
    checker4: false,
    checker5: false
  },
  {
    username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="0c6d6d6e6f4c69616d6560226f6361">[email protected]</a>",
    maker: true,
    checker1: false,
    checker2: false,
    checker3: false,
    checker4: false,
    checker5: false
  },
  {
    username: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5d3c3c3f3e2e2e391d38303c3431733e3230">[email protected]</a>",
    maker: false,
    checker1: true,
    checker2: false,
    checker3: false,
    checker4: false,
    checker5: false
  },
  {
    username: "dev_sams",
    maker: true,
    checker1: false,
    checker2: false,
    checker3: false,
    checker4: false,
    checker5: false
  },

];
export default function Downloads() {
  const classes = useStyles();

  const downloadsForm = useFormik({
    initialValues: {
      Username: "",
      Userlevel: ""
    },
    // validationSchema: downloadFormSchema,
    onSubmit: (values) => {
      alert(JSON.stringify(values, null, 2));
    }
  });
  const options = useMemo(() => {
    if (userList) {
      let levelList = [];
      for (let [key, value] of Object.entries(userList)) {
        if (value === true) {
          levelList.push({ value: key, label: key });
        }
      }
      return levelList;
    }
  }, [userList]);
  React.useEffect(() => {
    if (userList) {
      downloadsForm.setFieldValue("baseStr", options[0]);
    }
  }, [options, userList]);
  return (
    <Grid>
      <Grid item xs={12}>
        <Card color="primary" variant="outlined">
          <form onSubmit={downloadsForm.handleSubmit}>
            <CardContent>
              <Grid xs={12} item container>
                <Grid item xs={6} className={classes.formGrid}>
                  <TextField
                    id="outlined-select-currency"
                    select
                    label="User"
                    fullWidth
                    onChange={downloadsForm.handleChange}
                    value={downloadsForm.values.Username}
                    name="Username"
                    error={downloadsForm.errors.Username}
                    helperText={downloadsForm.errors.Username}
                    variant="outlined"
                    size="small"
                  >
                    {userList?.map((opt) => (
                      <MenuItem key={opt.username} value={opt.username}>
                        {opt.username}
                      </MenuItem>
                    ))}
                  </TextField>
                </Grid>
                {downloadsForm.values.Username && (
                  <Grid item xs={6} className={classes.formGrid}>
                    <TextField
                      id="outlined-select-currency"
                      select
                      label="Level"
                      fullWidth
                      onChange={downloadsForm.handleChange}
                      value={downloadsForm.values.Userlevel}
                      name="Userlevel"
                      variant="outlined"
                      size="small"
                    >
                      <MenuItem value={options}>{options}</MenuItem>
                    </TextField>
                  </Grid>
                )}
              </Grid>
              <Grid xs={12} item className={classes.formGrid}>
                <Box
                  display="flex"
                  alignItems="flex-end"
                  flexDirection="column"
                >
                  <Button variant="contained" color="primary" type="submit">
                    Submit
                  </Button>
                </Box>
              </Grid>
            </CardContent>
          </form>
        </Card>
      </Grid>
    </Grid>
  );
}

CodeSandBox Link

Answer №1

When choosing a username, there are important considerations to keep in mind:

  1. Obtain the available user level options for the selected user
  2. Automatically populate the user level with the first option

To streamline this process whenever the selected value changes, a custom method called handleUserNameChange should be created as shown below:

const handleUserNameChange = (e) => {
    const selectedUser = e.target.value;

    // Locate the specific user
    const user = userList.find((user) => user.username === selectedUser);

    // Generate an option list based on the user object's true property values
    const newOptions = Object.keys(user).reduce((optionList, key) => {
      if (user[key] === true) {
        optionList.push({ value: key, label: key });
      }
      return optionList;
    }, []);

    // Update the state to store the dynamically changing options
    setOptions(newOptions);

    // Update Formik state for username
    downloadsForm.setFieldValue("Username", selectedUser);

    // Update Formik state for userlevel by defaulting to the first option
    downloadsForm.setFieldValue("Userlevel", newOptions[0]?.value || "");
  };

Implement this method in the onChange event of your Username textfield.

onChange={handleUserNameChange}

Since the options vary based on the selected user, it is advisable to maintain a single state to manage these options.

View Demo

codesandbox

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for improving modularity in my frontend JavaScript code?

I'm currently developing a unique Node.js / Express application that visually represents text notes as a network to offer users a clear summary of the connections between different notes. The project heavily relies on frontend functionalities, requir ...

react-select seems to have a glitch where only the first option is rendering, but it is not visible. Additionally, when I try to select an option, the entire array seems to be disappearing

My backend is providing me with an array of flavors. This is how I am using it in my jsx: <div className="mb-3"> <Select options={flavorOptions} onChange={onSelectOption} value={flavor} /> </div> I have formatted the ...

When attempting to establish a connection with MongoClient, the function fails gracefully without generating an error

try { if (!conn) { console.log("Attempting to Connect to Atlas"); conn = await MongoClient.connect(process.env.MONGO_URL, { useNewUrlParser: true, useUnifiedTopology: true, }); console.log("Success ...

Error encountered: Provider '$rootScopeProvider' is not recognized - check for typos in the syntax

I am encountering an issue with the templateUrl in AngularJS. When I input this code into my editor and execute it, everything works flawlessly: HTML: <!DOCTYPE html> <html lang= "en"> <head> <meta charset="UTF-8" /> < ...

Setting radio button value while redirecting to a new page using Next.js

I'm in the process of developing a quiz application using Next.js. Within my app, I have implemented two buttons - one for navigating to the next question and another for going back to the previous question. When selecting an answer for a question usi ...

What is the best way to dismiss the additional modal popup?

Here is an example that I need help with: http://jsfiddle.net/zidski/Mz9QU/1/ When clicking on Link2 followed by Link1, I would like the Link2 box to close automatically. Is there anyone who can assist me with this issue? ...

The function purported by WEBPACK_MODULE_13___default(...) does not exist

Scenario : I've been working on a small library (let's call it myLibrary) using TypeScript and Webpack. Everything seemed to be running smoothly until I imported the library into a React application, which resulted in a crash. On the Library Sid ...

HTML is being incorrectly rendered by the Express framework

Looking to Use HTML as View Engine in Express? After going through the link, I attempted to start my server with an index.html file on port 8001. However, it failed to render correctly and showed an error in the console: Server Started Error: SyntaxError ...

Vue's keydown event will only fire when elements are in an active state

Encountering a strange issue while attempting to listen for keydown events in Vue.js. The keydown event is attached to a div tag that surrounds the entire visible area: <template> <div class="layout-wrapper" @keydown="handleKey ...

Tips for Saving JSON Response from Fetch API into a JavaScript Object

I am facing an issue trying to store a Fetch API JSON as a JavaScript object in order to use it elsewhere. The console.log test is successful, however I am unable to access the data. The Following Works: It displays console entries with three to-do items: ...

unable to modify the content within a div by clicking on a link

Lately, I've been experimenting with a code snippet I found on this fiddle: http://jsfiddle.net/unbornink/LUKGt/. The goal is to change the content of a div when clicking on links to see if it will work on my website. However, no matter which link I c ...

Combining arrays using JavaScript

I'm struggling to enhance the following code - it looks a bit messy: Here is my data format: date d1 d2 d3 d4 d5 d6 110522 5 1 3 5 0 7 110523 9 2 4 6 5 9 110524 0 0 0 0 1 0 110525 0 0 3 0 4 0 ... I am importing data from a text file using d3.j ...

Acquiring information from child functional components within a parent component using React

My components consist of functional components, where the parent component is a table and the child component is a row. The actions in the child component are controlled by data passed from the parent component. These controls utilize the useState hook to ...

How can background wait for executescript in a Chrome Extension?

I'm currently encountering an issue while developing my first Google Chrome Extension. In my background.js script, I have a scenario where I call script.js every second. Here's a simplified version of the code: script.js: /* Some code */ if (co ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Error: req.body or req.params.id is not defined in the current context (PUT and PATCH requests)

I'm experiencing an issue where both req.body and req.params.id are returning undefined even though I am using express.json() before the app.patch. I have tried changing the route to /:id, but that did not resolve the problem. Interestingly, it works ...

Exploring ways to run tests on a server REST API using testem

When using Testem, I have a config option called serve_files that handles serving the client-side code for me. However, I also need to run my server because it includes a REST API that the client side relies on. Is there a way to configure Testem to launc ...

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...

Removing the gap between the clicked point and the draw point in Html5 canvas

To better understand my issue, please refer to the image linked below: In the image, you can see that when I scroll down and click on the canvas to point a position, it creates space between the clicked point and where the line is drawn. Below is the cod ...

When accessing req.user in code not within a router's get or post method

Is there a way for me to access the data in the User schema outside of a post or get request? I am asking this because I would like to use this information elsewhere. The user schema is defined as follows: const mongoose = require('mongoose'); c ...