Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the Material UI component does not reflect this change as it is still tied to the original value object. This seems to be related to the dynamic creation of these components using a button.

The main problem lies in the value prop of the TextField component not being updated.

I handle the updates for these fields within the handleAnswersChange function. It checks if an answer already exists, and if it does, it updates it. If not, it creates a new one.

interface State {
  title: string;
  question: string;
  answers: Array<Answer>;
  correctAnswer: number;
}

interface Answer {
  answer: string;
  id: number;
}

export default function CreateQuestion() {
  const [answers, setAnswers] = React.useState<Array<JSX.Element>>([]);
  const [errorAnswer, setErrorAnswer] = React.useState(false);
  const [values, setValues] = React.useState<State>({
    title: "",
    question: "",
    answers: [{ answer: "", id: 1 }],
    correctAnswer: 1,
  });

  useEffect(() => {
    console.log(values);
  }, [values]);

  const handleChange =
    (prop: any) => (event: React.ChangeEvent<HTMLInputElement>) => {
      setValues({ ...values, [prop]: event.target.value });
    };
  
  const handleAnswersChange = (
    prop: any,
    id: number
  ) => (event: React.ChangeEvent<HTMLInputElement>) => {
    let answerIndex: number = 0;
    let doesExist: boolean = false;
    
    values.answers.map((answer, index) => {
      if (answer.id === id) {
        answerIndex = index;
        doesExist = true;
      }
    });
    
    if (doesExist) {
      const tempValues = values.answers;
      tempValues[answerIndex] = {
        answer: tempValues[answerIndex].answer + event.target.value,
        id: id,
      };
      setValues({
        ...values,
        [prop]: [...tempValues],
      });
    } else {
      setValues({
        ...values,
        [prop]: [...values.answers, { answer: event.target.value, id: id }],
      });
    }
  };

  const createAnswer = () => {
    const array = [...answers];
    array.push(
      <Box sx={{ m: 1 }} key={answers.length}>
        <FormControl
          sx={{ width: "60ch" }}
          variant="outlined"
          key={answers.length}
        >
          <TextField
            id="outlined-required"
            key={answers.length}
            label={"Answer " + (answers.length + 1)}
            value={values.answers[answers.length - 1].answer}
            onChange={
              handleAnswersChange("answers", values.answers.length)
            }
          />
        </FormControl>
      </Box>

Answer №1

Using an incorrect index can cause issues in your code. Make sure to map over the correct index to avoid placing items in the wrong position.

handleAnswersChange(event, "answers", values.answers.length);

Choosing the wrong index can lead to selecting the incorrect item. Remember that arrays start at 0, not 1.

Consider using `.map` along with the correct index for a more accurate representation of your data like in this example.

Instead of saving answers within themselves, store them in `values.answers` and render them using `.map`.

Reduce the number of keys you are using to improve readability and maintainability of your code.

Update: It looks like you are already storing answers in `values`, so there is no need to duplicate the array. Simply map over `values.answers` instead.

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

How can I create a redirect link in HTML that opens in a new window

I have a HTML page where I need to redirect to the next page. <a href="www.facebook.com" target="_blank">www.facebbok.com</a> Currently, it is redirecting to localhost:9000/dashboard/www.facebook.com But I only want to redirect to www.facebo ...

Solving filtering issues within React using a combination of conditions

I've been struggling to selectively remove an item from my array. The current filter I'm using is removing too much. Here is the array in question: [ { "domain": "domain1.com", "slug": "moni ...

How can I display the chosen option in the input field of a Material UI Autocomplete component?

How can I display the selected option in the textField? Which prop should I utilize? Although the options appear when clicked on the input field, the chosen option label is not displayed in the text field afterwards. Below is the code snippet I am curren ...

The Handsontable popup autocomplete editor is unfortunately truncated by the horizontal scrollbar

I have implemented an autocomplete feature on all columns in my project. However, I am facing an issue where the autocomplete editor gets cut off by the horizontal scrollbar. You can see the problem demonstrated in this jsfiddle link. Here is some code re ...

A step-by-step guide on transferring Data URI from canvas to Google Sheet using the fetch method

I am trying to send an image as base64 code to a Google sheet using fetch. However, I am encountering an error that says "data_sent is not defined" when I run my code. I need help identifying the problem and finding a solution to fix it. For reference, & ...

What are the steps to reach the breakpoint properties in the theme toolbar?

I am currently utilizing the material-ui themeProvider and attempting to retrieve all height values from the default theme within a style: makeStyles(theme => createStyles({ ... marginTop: -theme.mixins.toolbar.minHeight, // This is functional [`${th ...

jsonAn error occurred while attempting to access the Spotify API, which resulted

Currently, I am working on acquiring an access Token through the Client Credentials Flow in the Spotify API. Below is the code snippet that I have been using: let oAuthOptions = { url: 'https://accounts.spotify.com/api/token', method: ' ...

What is the best way to incorporate the chosen value into an array?

I'm currently working on implementing an Autocomplete feature and need some help with it: var arr=[]; const changeHandler = (value) => { // arr.push(value); // console.log("arr",arr) setItem(arr) } ...

Ways to implement a fixed navigation bar beneath the primary navbar using ReactJS

Utilizing ReactJS, I am endeavoring to create a secondary (smaller) navbar in the same style as Airtable's product page. My primary navbar is situated at the top and transitions from transparent to dark when scrolled. The secondary bar (highlighted in ...

Error encountered while trying to install eslint-plugin-react with an incompatible engine

Hello, I am a new React user and I am running into an issue in my terminal after installing eslint-plugin-react and eslint-plugin-react-hooks. npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '@es-joy/<a href="/cdn-cgi/l/emai ...

Take away the boundary of the TexfField

Recently, I've been using @Mui for React and decided to utilize it to create a form. However, upon focusing on TextField, I noticed a border line similar to the one shown in the image below: https://i.stack.imgur.com/QCorb.png This is how my code loo ...

What are the consequences of submitting a form to a different website through POST method?

Dealing with a CMS that does not offer an easy way to add a NodeJS route for handling form data can be quite challenging. I'm considering the following setup - would this be considered bad practice or unsafe? Server 1 (Ghost CMS) : www.domain.com &l ...

What is the method to retrieve the total number of days in a moment-jalaali using NodeJS?

I'm trying to determine the number of days in the moment-jalaali package for NodeJS. Despite checking their API on GitHub, I couldn't find any reference to a specific method like numOfDay. ...

Why is the useHistory hook in React failing to function properly?

When I try to launch my web application using npm start, an error occurs stating that the useHistory hook has not been downloaded, despite having installed the latest version of react-router-dom. Can someone explain why this is happening? Here is a screens ...

This error message occurs when trying to access JSON keys from an object with an invalid operand in the 'in' operation

Check out the fiddle I created here: http://jsfiddle.net/kc11/h6nh1gvw/2/ I'm attempting to extract keys from a JSON string using this code: var keys = $.map(a, function(element,key) { return key; }); . But unfortunately, I keep encountering the er ...

Dealing with errors in getServerSideProps in Next.js by utilizing next-connect

Recently, I've been working with Next.js and utilizing the next-connect library to manage middlewares in my project. However, I'm encountering some difficulties when it comes to handling errors while using multiple middlewares within the getServ ...

The React Hook useEffect is missing a dependency: 'handleLogout'. Make sure to either add it to the dependency array or remove it from the useEffect hook

import { useState, useEffect } from "react"; import LoginModal from "./LoginModal"; import { NavLink, useLocation, useNavigate } from "react-router-dom"; import { useDispatch } from "react-redux"; import { userLogout ...

Positioning Material-UI Drawer within a designated div: A comprehensive guide

I am currently incorporating the Material-UI React Drawer into my project. Is there a way to restrict the drawer to a specific section of the page instead of it taking up the entire window? I attempted setting an absolute position for the root component in ...

Material UI: After upgrading to version 5, the priority of useStyles (makeStyles) has been reduced

After upgrading to Material Ui version 5, I noticed that all my styles were being given lower priority in the stylesheet. const useStyles = makeStyles((theme) => ({ drawer: { [theme.breakpoints.down('md')]: { width: 0, ...

React and Redux: Error Alert - A change in state was detected during dispatch operations

While using 'controlled' components (utilizing setState() within the component), I am encountering an intermittent error when trying to save form data. The UserForm's onSave function calls back to the saveUser method in the component code pr ...