Home > Enterprise >  Stop rendering UseEffect of Click of a specific function
Stop rendering UseEffect of Click of a specific function

Time:07-20

In my Application when ever i change the number i want run the UseEffect Hook and re-render the updated values in the array which is working, but one condition i don't want to run the use UseEffect Hook is when i click addRow function i want bank field should be added in the rows except the number

JsCode

     const [number, setNumber] = useState(3);
     const [data, setData] = useState([]);
     const [insValue,setInstValue]=useState(90); 


useEffect(() => {
    const list = [];
    for (let i = 1; i <= number; i  ) {
      let ins = instValue/number;
      list.push({
        insNo: i,
        installmentAmount: ins,
        chequeNumber: '',
      });
    }
 
    setData(list);
    
  }, [number]);

  const addRow = () => {
    setNumber((number) => number   1);
    console.log('Add item clicked');
    data.push({
      insNo: number   1,
      installmentAmount: '',
      chequeNumber: ''
    });
    const list = [...data];
    setData(list);
  };

Html

<div onClick={addRow}>
        ADD ROW
</div>

currently what it is happening is when i click on add row number get changed and useffect Runs and data get updated i need is blank field in the row on the last object of an array

Output Getting

[{"insNo":1,"installmentAmount":22.5,"chequeNumber":""},
{"insNo":2,"installmentAmount":22.5,"chequeNumber":""}
{"insNo":3,"installmentAmount":22.5,"chequeNumber":""}
{"insNo":4,"installmentAmount":22.5,"chequeNumber":""}]

Output i need on click of addRow

 [{"insNo":1,"installmentAmount":30,"chequeNumber":""},
    {"insNo":2,"installmentAmount":30,"chequeNumber":""}
    {"insNo":3,"installmentAmount":30,"chequeNumber":""}
    {"insNo":4,"installmentAmount":"","chequeNumber":""}]

CodePudding user response:

The data is refreshed again into the useEffect when you change number, losing all data.

You can avoid change number state at click, since the new data is already being saved manually.

setNumber((number) => number 1);

CodePudding user response:

It's hard to understand what you exactly want.

But according to your code, you can't get the desired result. Because you increase number and add a new row with empty values. And useEffect updates your array data again. So the installmentAmount in the last row will be filled.

To avoid it, you can change the code block like the following:

      list.push({
        insNo: i,
        installmentAmount: i == number? '' : instValue/number,
        chequeNumber: '',
      });
  • Related