A
A
andrey_chirkin2022-03-10 09:50:57
JavaScript
andrey_chirkin, 2022-03-10 09:50:57

Why is the data on the wrong row displayed in the form?

Hello. I have implemented the ability to use the arrows to swap rows in the table. But when you open the form to edit the data for a line, the data of the wrong line is substituted there. Please tell me how to fix this?

Displaying table rows in map:

import React from 'react';
import TechStore from "../../../../../TechStore";
import ButtonEditOperation from "../ButtonEditOperation/ButtonEditOperation";
import ButtonAddContentOperation from "../ButtonAddContentOperation/ButtonAddContentOperation";
import ButtonDeleteOperation from "../ButtonDeleteOperation/ButtonDeleteOperation";
import OutputOperation from "./OutputOperation/OutputOperation";
import {observer} from "mobx-react";

const OutputOperations = observer(({item, index}) => {

    const {dataTable} = TechStore

    const handleClick = (index, item) => (
        () => {
            dataTable.forEach((operation) => {
                operation["clicked"] = false
            })
            item["clicked"] = true
            dataTable[index] = item
            console.log('clickTR')
        }
    )

    return (
        <tr
            style={dataTable[index]["clicked"] ? {
                backgroundColor: "#E4F2FE"
            } : {}}
            onClick={handleClick(index, item)}
        >
            <OutputOperation
                item={item}
                index={index}
            />
            <td>
                <div className="groupButton">
                    <ButtonEditOperation index={index} item={item}/>
                    <ButtonAddContentOperation index={index}/>
                    <ButtonDeleteOperation index={index} item={item}/>
                </div>
            </td>
        </tr>
    )
})

export default OutputOperations


Form opening logic and validation:
import React, {useState} from 'react'
import '../../OperationTable.css'
import {
  Button,
  Dialog,
  DialogActions,
  DialogContent,
} from "@mui/material"
import EditIcon from '@mui/icons-material/Edit'
import {observer} from "mobx-react"
import OutputOperationTextField from "./OutputOperationTextField/OutputOperationTextField"
import OutputOperationCheckbox from "./OutputOperationCheckbox/OutputOperationCheckbox"
import TechStore from "../../../../../TechStore"
import HeaderModalWindow from "../../../HeaderModalWindow"
import {toJS} from "mobx";

const ButtonEditOperation = observer(({index, item}) => {

  const {dataTable} = TechStore
  const [operationItem, setOperationItem] = useState(item)
  const [open, setOpen] = useState(false)

  //-------------------------initialValidation-------------------

  let copyItem = JSON.parse(JSON.stringify(item))
  const fieldsCopyItemDeleted = ['id', 'OO', 'OTK', 'PZ', 'KPS', 'transition', 'equipment', 'adaptation', 'tool', 'clicked']
  for (const key in copyItem) {
    if (fieldsCopyItemDeleted.includes(key)) {
      delete copyItem[key]
    } else {
      copyItem[key] = false
    }
  }

  const [isValid, setIsValid] = useState(copyItem)

  //-------------------------initialValidation-------------------

  const handleClickOpen = (event) => {
    event.stopPropagation()
    console.log('clickEDIT')
    setOpen(true)
  }

  const handleClose = () => {
    setOpen(false)
  }

  const handleInputAndCheckboxChange = (event) => {
    const {name, type} = event.target
    const value = (type === 'checkbox') ? event.target.checked : event.target.value
    setOperationItem({...operationItem, [name]: value})
  }

  const handleSubmit = (event) => {

    event.preventDefault()

    const letterCheck = /^[а-яА-Я][а-я А-Я]+[а-яА-Я]$/
    const numberCheck = /^[0-9]+$/

    let copyIsValid = JSON.parse(JSON.stringify(isValid))

    for (const key in isValid) {
      if (key === 'nameOperation') {
        letterCheck.test(operationItem[key]) ? copyIsValid[key] = false : copyIsValid[key] = true
      } else {
        numberCheck.test(operationItem[key]) ? copyIsValid[key] = false : copyIsValid[key] = true
      }
    }

    setIsValid(copyIsValid)

    const valuesIsValid = Object.values(copyIsValid)
    if (!valuesIsValid.includes(true)) {
      dataTable[index] = operationItem
      setOpen(false)
    }

  }

  return (
    <>
      <Button
        variant="text"
        onClick={handleClickOpen}
      >
        <EditIcon fontSize="small"/>
      </Button>
      <Dialog
        open={open}
        onClose={handleClose}
        className="buttonEditItemOperationModalWindow"
      >
        <HeaderModalWindow header="Редактировать данные операции" handleClose={handleClose}/>
        <DialogContent dividers>
          <form method="POST" onSubmit={handleSubmit}>
            <OutputOperationTextField
              operationItem={operationItem}
              handleInputAndCheckboxChange={handleInputAndCheckboxChange}
              nameFieldFirstInput="numberOperation"
              nameFieldSecondInput="nameOperation"
              nameFieldThirdInput="level"
              nameFieldFourthInput="workshop"
              nameFieldFifthInput="area"
              isValid={isValid}
            />
            <OutputOperationCheckbox
              operationItem={operationItem}
              handleInputAndCheckboxChange={handleInputAndCheckboxChange}
              nameFieldFirstInput="OO"
              nameFieldSecondInput="OTK"
              nameFieldThirdInput="PZ"
              nameFieldFourthInput="KPS"
            />
            <DialogActions>
              <Button
                type="submit"
                variant="contained"
                color="success"
              >
                Сохранить
              </Button>
            </DialogActions>
          </form>
        </DialogContent>
      </Dialog>
    </>
  )
})

export default ButtonEditOperation


Button logic to move rows up and down:
import React from 'react'
import {Button} from "@mui/material";
import ExpandLessIcon from "@mui/icons-material/ExpandLess";
import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import TechStore from "../../TechStore";
import {observer} from "mobx-react";
import {toJS} from "mobx";

const RowMoveUpAndDown = observer(() => {

    const {dataTable, radioButtons} = TechStore

    let index = 0
    dataTable.forEach((operation, indexOperation) => {
        if (operation['clicked']) {
            index = indexOperation
        }
    })

    const buttonStyle = {
        but1: {
            minWidth: '30px',
            padding: 0,
            marginRight: '5px'
        },
        but2: {
            minWidth: '30px',
            padding: 0,
        }
    }

    const handleClickRowUp = () => {
        let strPrev
        if (index === 0) {
            strPrev = dataTable[index]
            dataTable.splice(index, 1)
            dataTable.splice((dataTable.length), 0, strPrev)
        } else {
            strPrev = dataTable[index - 1]
            dataTable[index - 1] = dataTable[index]
            dataTable[index] = strPrev
        }

        dataTable.forEach((operation) => {
            operation["clicked"] = false
        })

        if (index === 0) {
            dataTable[dataTable.length - 1]["clicked"] = true
        } else {
            dataTable[index - 1]["clicked"] = true
        }
    }

    const handleClickRowDown = () => {
        let strPrev
        if (index === (dataTable.length - 1)) {
            strPrev = dataTable[dataTable.length - 1]
            dataTable.splice((dataTable.length - 1), 1)
            dataTable.splice(0, 0, strPrev)
        } else {
            strPrev = dataTable[index + 1]
            dataTable[index + 1] = dataTable[index]
            dataTable[index] = strPrev
        }

        dataTable.forEach((operation) => {
            operation["clicked"] = false
        })

        if (index === (dataTable.length - 1)) {
            dataTable[0]["clicked"] = true
        } else {
            dataTable[index + 1]["clicked"] = true
        }
    }

    return (
        <>
            {(radioButtons["content"] || radioButtons["norm"]) ? (
                <>
                    <Button
                        disabled
                        variant="contained"
                        sx={buttonStyle.but1}
                        className="buttonStyle"
                        onClick={handleClickRowUp}
                    >
                        <ExpandLessIcon/>
                    </Button>
                    <Button
                        disabled
                        variant="contained"
                        sx={buttonStyle.but2}
                        onClick={handleClickRowDown}
                    >
                        <ExpandMoreIcon/>
                    </Button>
                </>

            ) : (
                <>
                    <Button
                        variant="contained"
                        sx={buttonStyle.but1}
                        className="buttonStyle"
                        onClick={handleClickRowUp}
                    >
                        <ExpandLessIcon/>
                    </Button>
                    <Button
                        variant="contained"
                        sx={buttonStyle.but2}
                        onClick={handleClickRowDown}
                    >
                        <ExpandMoreIcon/>
                    </Button>
                </>

            )}

        </>
    )
})

export default RowMoveUpAndDown


Source table and form with data:
62299fb7dffd9269306746.png
After moving, the data does not match:
62299f5da9d6c148805701.png

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question