I am trying running a function after a click on a button. This function is fetching data from backend and stores the response data in a variable called (rows), running setRows(output), with output being formatted data from the response.
The issue is that in the first run, the rows variable is empty but the output variable is as it should be. After the second click on the button, everything seems fine, the rows are set. I would like to know what is causing this?
export default function Datatable() {
const [rows, setRows] = useState({});
async function fetchData() {
let id = 0;
const res = await fetch('/table/data).then(res => res.json());
const data = res.results.bindings;
const output = Object.keys(data).map(key => {
return {id: id++, opNr: data[key].opNr.value, opName: data[key].opName.value };
})
setRows(output);
console.log(output);
console.log(rows);
}
return (<button type="button" class="a-button " onClick={fetchData}> </button>);
}