reactjs - update setState with array values
Trying to open the modal and expecting to see the state value you just enqueued won't ever work, due to the way React asynchronously processed enqueued state updates.
What I suggest then is to place the modal open triggering into a setTimeout
call so that the function can complete and allow React to process the enqueued state update. Just enough to get the timeout callback to execute on a tick after the state update was processed, just about any timeout should be sufficient, but this is a bit hackish and obviously you will want to fine-tune this specifically to your app.
const selectedSystem = (row, action) => {
selectedsysID = {...selectedSystemID, 'SYSTEMID':row.SYSTEMID}
getDependentSystems();
setTimeout(() => {
(action === 'AddDep') ? openModal() : openOtherModal();
}, 17); // delay by about 1 minimum render cycle
};
An alternative would be to store the action in state and use an useEffect
hook to issue the side-effect up opening the modal.
const [savedAction, setSavedAction] = useState();
const [dependentSystems, setDependentSystems] = useState([]);
const getDependentSystems = async (action) => {
const response = await axios.get('/GETAPI' + selectedSysID.SYSTEMID);
console.log("LIST OF DEPENDENT SYSTEM", response.data);
setDependentSystems(response.data);
setSavedAction(action);
};
useEffect(() => {
if (savedAction) {
(action === 'AddDep') ? openModal() : openOtherModal();
setSavedAction(null);
}
}, [savedAction]);
const selectedSystem = (row, action) => {
selectedsysID = {...selectedSystemID, 'SYSTEMID':row.SYSTEMID}
getDependentSystems(action);
};
Just stick the getDependentSystems as a onClick handler of a button.
const [dependentSystems, setdependentSystems] = useState([]);
const getDependentSystems = async () => {
const response = await axios.get('/GETAPI' + SYSTEMID)
console.log("LIST OF DEPENDENT SYSTEM", response.data)
setdependentSystems(response.data)
}
On the JSX part:
return <button onClick={getDependentSystems}>GET SYSTEM</button>