How to avoid Maximum update depth exceeded Reactjs

I tried to display some csv content in reactjs application using below code. when i click the button it should call the api and get the response.i need to show the response in table formate and when i submit i need to save the data. Getting response and Saving is working fine for me but my issue is when i click the side menu to for fetch the selected data my state not updating properly to display the selected value data i need to click more than three times. so i tried with useeffect its with dependency its wokring fine . but its showing memory issue. i am new to react i tried many ways its showing maximum exceed error. so how to fix it in below code

import './tabs.scss'
import React, { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux';
import { ListGroup, Nav, Tab } from 'react-bootstrap'
import { jmxView } from '../../APIPath';
import './tabs.scss'
import { getViewAttachment } from '../../../../ducks/testcase/gettestcase/actions';
import { testcase } from '../../APIPath';
import { toast } from 'react-toastify';
import { Buffer } from 'buffer';
const Parameters = ({ selectedtestcaseId, hideTestTab }) => {

  const [csvattachment, setcsvattachment] = useState({})
  const [slectedattachementId, setslectedattachementId] = useState()
  const [viewcsv, setviewcsv] = useState()
  const dispatch = useDispatch();
  useEffect(() => {
    let testcaseId = {
      "testcaseId": selectedtestcaseId
    }
    dispatch(getViewAttachment(testcaseId))
  }, [])

  const getthreadGroup = useSelector(state => state.getthread);

  useEffect(() => {
    if (getthreadGroup.attachment.attchements) {
      let csvfile = getthreadGroup?.attachment?.attchements.filter(value => {
        return value.extension == 'csv'
      })
      setcsvattachment(csvfile)
      if (Object.keys(csvfile).length !== 0) {
        getCSV(csvattachment[0]?.attachmentid)
      }
    }

  }, [getthreadGroup])

  const getCSV = async (attachmentid) => {
    setslectedattachementId(attachmentid)
    if (attachmentid) {
      await fetch(`${jmxView}${attachmentid}`)
        .then((res) => res.text())
        .then((res) => {
          setviewcsv(res)
          formatCsv()
        })

    }


  }

  const [csvHead, setcsvHead] = useState([])
  const [csvformFields, setcsvformFields] = useState([{}])
  const [formatData, setformatData] = useState([])

  const formatCsv = () => {
    console.log(csvHead)
    if (viewcsv) {
      let splitVlaues = viewcsv?.split('rn')
      setcsvHead(splitVlaues[0]?.split(','))
      let allData = []
      for (let i = 1; i < splitVlaues.length - 1; i++) {
        let a = splitVlaues[i].split('"');
        let filteredValue = a.filter(x => x && x != ',');
        allData.push(filteredValue)

      }
      setformatData(allData)
      var newval = formatData.map(val => {
        return val.reduce((result, field, index) => {
          result[csvHead[index]] = field;
          return result;
        }, {})
      })
      setcsvformFields(newval)
    }
  }


  useEffect(() => {
    formatCsv()
  }, [csvformFields])
  const submitForm = async () => {

    let base64data = Buffer.from(csvformFields).toString('base64')
    let payload = {
      "attachementId": slectedattachementId,
      "testcaseId": selectedtestcaseId,
      "attachementType": "csv",
      "attachementContent": base64data
    }

    await fetch(`${testcase}/testcase/saveCSVParameter`,
      {
        method: 'POST',
        body: JSON.stringify(payload),
        headers: {
          "Content-Type": "application/json",
        },
      }
    )
      .then((response) => response.json())
      .then((result) => {

        toast.success(result.message)
      })
      .catch((error) => {

      });
  }

  const handleFormChange = (i, e) => {
    let data = [...csvformFields];
    data[i][e.target.name] = e.target.value;
    setcsvformFields(data)

  }

  return (
    <div className="tab_content pt-2 h-100">
      <div className="content_panel">
        <div className="row py-2">
          <div className="col-sm-3">
            <div className="titleLabel p-2">Parameter Name</div>
            <div className="vertical_nav">
              <Nav variant="pills" className="flex-column">
                {
                  csvattachment.length > 0 &&

                  <>
                    {
                      csvattachment.map((value, index) => (
                        <>
                          <Nav.Item key={index}><Nav.Link eventKey={index} onClick={() => getCSV(value.attachmentid)}>{value.originalfilename} <i class="bi bi-chevron-right"></i></Nav.Link></Nav.Item>
                        </>
                      ))
                    }
                  </>
                }

              </Nav>
            </div>
          </div>
          <div className="col-sm-9 ps-4">
            <div className="titleLabelOutline p-2">Parameter Value</div>
            <div className="row updateParameterField mt-4">


              <div className="col-md-12">
                <table className="table table-striped table-bordered parameter-display">
                  <thead>
                    <tr>
                      {csvHead.map((val, i) => <td key={i}>{val}</td>)}
                    </tr>
                  </thead>
                  <tbody>
                    <>
                      {csvformFields?.map((d, index) => (
                        <tr>
                          {Object.keys(d).map(prop => (
                            <>
                              <td><input type="text" name={prop} value={d[prop]} onChange={(e) => handleFormChange(index, e)} /></td>

                            </>
                          ))}
                        </tr>
                      ))}
                    </>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
        </div>

      </div>
      <div className="button_panel gap-3">
        <button className="btn btn-sm btn_secondary px-3" onClick={hideTestTab}>Cancel</button>
        <button className="btn btn-sm btn_primary px-4" onClick={submitForm}> Save</button>
      </div>
    </div>
  )
}

export default Parameters

I tried to call “csvformFields” using useEffect its thrwoing maximum exceed error and also i tried with “csvHead ” varibale still the same.. How can i fix the maxmium exceed error in the above code. where i am making the mistake. which variable i need to add as dependency array in useEffect and why??

below is the error which i am getting

*

Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on every render

*

Leave a Comment