React JS does not allow TextField and Select to change

I am relatively new to full stack development and I am currently working on a project to enhance my understanding of frontend development with React JS. While working on this project, I have been using Redux without any issues so far. However, I am facing an obstacle in writing a list of fields from a Firebase document that I can edit based on the existing data and then send it back to the server. The problem is, each TextField and Select component does not update their values as expected:

class PostDialog extends Component {
  state = {
    open: false,
    oldPath: '',
    newPath: '',
    Code:"",
    barrCode:"",
    color:"",
    size:"",
    qnt:"",
    brand:"",
    cat:"",
    price:"",
    createdAt:"",
    descr:"",
    errors:{}
  };
  componentDidMount() {
    if (this.props.openDialog) {
      this.handleOpen();
    }
  }
  handleOpen = () => {
    let oldPath = window.location.pathname;

    const { userHandle, postId } = this.props;
    const newPath = `/inv/${postId}`;

    if (oldPath === newPath) oldPath = `/inv`;

    window.history.pushState(null, null, newPath);

    
    this.props.getPost(this.props.postId);
    this.setState({ open: true, oldPath, newPath, size: this.props.size });
  };
  handleClose = () => {
    window.history.pushState(null, null, this.state.oldPath);
    this.setState({ open: false });
    this.props.clearErrors();
  };

  handleChange=(event)=>{
    this.setState({[event.target.name]: event.target.value})
  };
  onTodoChange(value){
    this.setState({
      barrCode: value
    });
}
  render() {
    const {errors} = this.state;
    const {
      classes,
      post: {
        postId,
        Code, barrCode, color,size,qnt,brand,cat,price,createdAt,descr,available
      },
      UI: { loading }
    } = this.props;


    const ITEM_HEIGHT = 48;
        const ITEM_PADDING_TOP = 8;
        const MenuProps = {
            PaperProps: {
              style: {
                maxHeight: ITEM_HEIGHT * 4.5 + ITEM_PADDING_TOP,
                width: 250,
              },
            },
        };

    const dialogMarkup = loading ? (
      <div className={classes.spinnerDiv}>
        <CircularProgress size={200} thickness={2} />
      </div>
    ) : (
      <Grid container spacing={16}>
        <Grid item sm={7}>
          <hr className={classes.invisibleSeparator} />
          <Typography variant="body2" color="textSecondary">
            {dayjs(createdAt).format('h:mm a, MMMM DD YYYY')}
          </Typography>
          <hr className={classes.invisibleSeparator} />
          <TextField
                                name="barrCode"
                                type="text"
                                label="Codice a Barre"
                                placeholder="111111111"
                                rows="1"
                                error={errors.barrCode ? true : false}
                                helperText={errors.barrCode}
                                className={classes.TextField}
                                value={barrCode}
                                onChange={this.handleChange}
                                fullWidth
                            />
                            <TextField
                                name="price"
                                type="text"
                                label="Prezzo"
                                placeholder="111111111"
                                rows="1"
                                error={errors.price ? true : false}
                                helperText={errors.price}
                                className={classes.TextField}
                                value={price}
                                onChange={this.handleChangePrice}
                                fullWidth
                            />
                            <Box display="flex" flexDirection="row">
                              <Box>
                              <InputLabel id="brand">Marca</InputLabel>
                                        <Select
                                            labelId="Marca"
                                            id="brand"
                                            value={brand}
                                            onChange={this.brandChange}
                                            input={<Input />}
                                            MenuProps={MenuProps}
                                        >
                                        {brands.map((brand) => (
                                            <MenuItem value={brand}>
                                            {brand}
                                            </MenuItem>
                                        ))}
                                        </Select>
                              </Box>
                              <Box>
                              <InputLabel id="cat">Categoria</InputLabel>
                                        <Select
                                            labelId="Marca"
                                            id="cat"
                                            value={cat}
                                            onChange={this.catChange}
                                            input={<Input />}
                                            MenuProps={MenuProps}
                                        >
                                        {cats.map((cat) => (
                                            <MenuItem value={cat}>
                                            {cat}
                                            </MenuItem>
                                        ))}
                                        </Select>
                              </Box>
                              
                            </Box>
                            
                             
        </Grid>
        <hr className={classes.visibleSeparator} />
        <DeletePost postId={postId} />
          {/* <CommentForm postId={postId} /> */}
          {/* <Comments comments={comments} /> */ 
      </Grid>
    );
    return (
      <Fragment>
        <MyButton
          onClick={this.handleOpen}
          tip="Modifica"
          tipClassName={classes.expandButton}
        >
          <UnfoldMore color="primary" />
        </MyButton>
        <Dialog
          open={this.state.open}
          onClose={this.handleClose}
          fullWidth
          maxWidth="sm"
        >
          <MyButton
            tip="Close"
            onClick={this.handleClose}
            tipClassName={classes.closeButton}
          >
            <CloseIcon />
          </MyButton>
          <DialogContent className={classes.dialogContent}>
            {dialogMarkup}
          </DialogContent>
        </Dialog>
      </Fragment>
    );
  }
}

PostDialog.propTypes = {
  clearErrors: PropTypes.func.isRequired,
  getPost: PropTypes.func.isRequired,
  postId: PropTypes.string.isRequired,
  post: PropTypes.object.isRequired,
  UI: PropTypes.object.isRequired
};

const mapStateToProps = (state) => ({
  post: state.data.post,
  UI: state.UI
});

const mapActionsToProps = {
  getPost,
  clearErrors
};

export default connect(
  mapStateToProps,
  mapActionsToProps
)(withStyles(styles)(PostDialog));

I am seeking guidance on how to resolve this issue. Can anyone provide suggestions on what steps to take next?

Answer №1

give this a try

handleChange=(event)=>{
    this.setState({ ...this.state, event.target.name: event.target.value });
  };

Make sure to update the values in html inputs to look like value={this.state.[somevalue]}

<TextField
    name="barrCode"
    type="text"
    label="Codice a Barre"
    placeholder="111111111"
    rows="1"
    error={errors.barrCode ? true : false}
    helperText={errors.barrCode}
    className={classes.TextField}
    value={this.state.barrCode}
    onChange={this.handleChange}
    fullWidth
/>

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

Is today within the current week? Utilizing Moment JS for time tracking

There is a problem that I am facing. Can you assist me in determining whether the day falls within the current week? I am currently developing a weather forecast service and need to validate if a given day is within the current week. The only clue I have ...

Algorithm for encryption and decryption using symmetric keys

Can anyone recommend a reliable symmetric-key encryption algorithm that works seamlessly with both JavaScript and Java programming languages? I attempted to implement one myself, but encountered some complications related to encoding. ...

The attempt to execute 'removeChild' on 'Node' was unsuccessful because parameter 1 is not the correct type. Although it did remove the elements from the DOM, it only did so once

It's quite a challenge I'm facing!!! Although there have been similar questions asked before, they were all for specific scenarios. I am currently developing a tictactoe game using the module design pattern. The function below helps me create tw ...

Is it possible to execute my react project on my smartphone while connected to the same network?

Is there a way for me to access my localhost:3000 react app on my smartphone? I'm using vite to launch the app. I attempted to connect both devices to the same network and access it from my phone. ...

Why does trying to package a Windows app on OSX prompt a request for Wine installation?

For several months, I have been successfully utilizing Electron on macOS (10.11.6) to create and package both OSX and Windows applications. My current setup includes electron v1.7.3 and "electron-packager" "^8.5.2", all of which have not been updated in a ...

Skipping every third index in a JQuery .each loop after removing an element

I have a project where I need to display elements in rows of 4, and when an element is deleted, I want the remaining elements to shift up. To achieve this, I am currently assigning a class "last" to every fourth item after a deletion and inserting a spacer ...

Constantly refreshing MUI Paper components

I am currently in the process of developing a fitness app that includes a timer. I have chosen to use MUI for this project. However, I've encountered an issue that is causing my app to break. Whenever I incorporate the Paper components or any Item bas ...

"Utilizing Material UI's Stack component for a responsive, full-width

Is there a way to achieve full width for Item 2 without using width:100% with flexbox? <Box sx={{ width: '100%' }}> <Stack spacing={2} alignItems="flex-start"> <Item>Item 1</Item> <Item>Item 2< ...

Passing a Scope to ES6 Template Literals: How to Ensure they are Interpreted Correctly?

I've recently started utilizing template literals to create an error generator. Although I have functional code, I find myself having to define the list of potential errors within the constructor scope, and this is not ideal for me. Is there a way t ...

What steps can I take to keep the page from automatically redirecting back to the login page after I have successfully

Upon logging in, if the user decides to click on the browser's go back button, they will find themselves redirected back to the login page. I attempted using router.push: if (session) { router.push('/homepage'); } return ( ...

When using getStaticPaths, an error is thrown stating "TypeError: segment.replace is not a function."

I am a beginner when it comes to using Next.js's getStaticPaths and I recently encountered an error that has left me feeling lost. Below is the code I have written (using query from serverless-mysql): export async function getStaticPaths() { cons ...

What is the best method for calculating the total sum by multiplying the values in an array?

In my current project, I have an array consisting of multiple objects, each containing a property named "amount". My goal is to sum up all these amount values to get the total. Initially, I attempted to use a for loop but encountered an issue where settin ...

Error: The "res.json" method is not defined in CustomerComponent

FetchData(){ this.http.get("http://localhost:3000/Customers") .subscribe(data=>this.OnSuccess(data),data=>this.OnError(data)); } OnError(data:any){ console.debug(data.json()); } OnSuccess(data:any){ this.FetchData(); } SuccessGe ...

What is the accurate way to write the ID selector for the select-option-selected in JQuery?

When it comes to extracting a value from a Select-Option using jQuery, the following syntax can be used. I have successfully retrieved data using this method. $( "#Vienna\\.rail0\\.track option:selected" ).text() However, there is an ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

React - callbackFromApp function is executing only one time when clicked

Whenever I click a button within my child React module, it is meant to increment the timer and then pass back the timer in minutes and total seconds to the parent component where it will be stored as state. The issue I am facing is that when I click the b ...

Issue with utilizing apexcharts-react and useEffect

Need some assistance with my weather app. In the Chart component, the options and series display as [object Object]. Whenever a change is made in the code, it reflects on the graph. I suspect the issue lies within the useEffect, but unsure how to resolve i ...

The usage of the bootstrapTable() function creates a gap below the displayed table information

Currently, I am working on incorporating a table into my webpage that will load data from an API. After some research, I found a Bootstrap table library to assist with this task. However, I have encountered an issue with setting the table height dynamicall ...

Converting milliseconds into days, hours, minutes, and seconds using Angular

Currently, I am attempting to convert milliseconds to the format dd:hh:mm:ss. For example, given 206000 milliseconds. The desired format for this value would be: 00:00:03:26. However, when utilizing the following code: showTimeWithHour(milliSeconds: numb ...

Error encountered with underscore template - Unforeseen SyntaxError: Unexpected token <

I encountered an error when attempting to load one of my underscore templates. It seems to be related to an issue in the for loop, which I suspect should be a .each loop, but I'm still trying to grasp its structure. Here is a snippet of my template: ...