Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
640 views
in Technique[技术] by (71.8m points)

javascript - React setState not updating state in AG Grid onCellValueChanged callback

I am using Ag Grid in my React.js project. I want to increase the count value if the cell value changes. I am passing my handleChange function to onCellValueChanged callBack. Every time cell value changes it triggers my handleChange function, but the issue is count value is always 0 regardless updating it through setState(count + 1). Can anyone help with this?

I have posted an example on StackBlitz to reproduce this issue :
https://stackblitz.com/edit/ag-grid-react-hello-world-zmsvf5?embed=1&file=index.js

minimilastic example of this issue

question from:https://stackoverflow.com/questions/65941107/react-setstate-not-updating-state-in-ag-grid-oncellvaluechanged-callback

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your problem is to execute de loading function without useEffect. It causes too many re-renders because in each setRowData, the component render again.

This is the solution:

    function loadDataFromServer() {
    setTimeout(() => {
      setRowData([{ make: "Toyota" }, { make: "Toyota" }, { make: "Toyota" }]);
    }, 1000);
  }

  useEffect(() => {
    setCount(prevCount => prevCount + 1);
  }, [rowData]);

  useEffect(() => {
    loadDataFromServer();
  }, []);

  // function handleChange() {
  //   //here Count will always remain 0 (the value provided initially)
  //   console.log("Count => ", count);
  //   setCount(count + 1);
  // }

  return (
    <div>
      <h1>Count Changes: {count}</h1>
      <div className="ag-theme-alpine" style={{ height: 400 }}>
        <AgGridReact rowData={rowData}>
          <AgGridColumn
            field="make"
            editable={true}
            // onCellValueChanged={handleChange}
          />
        </AgGridReact>
      </div>
    </div>
  );
};

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...