Below is the code for the functional component. I'm updating the state inline with onClick event handler and it displays the updated data inside the useEffect. But as soon as the control comes out of the useEffect, the state variable 'data' gets back to its previous data. I have tried updating it without useEffect first, but the problem is the same. I'm not able to access the updated state variable in other functions.
function Task(props) {
var initialData = {
id: '1',
content: 'somecontent',
linkedPage: 'somepage',
};
const [data, setData] = useState(initialData);
useEffect(() => {
console.log(data);
}, [data]);
const saveTask = () => {
console.log(data);
const obj = {
name: data.content,
id: data.id,
};
};
this is the button where I'm updating the state
<button
className="btn btn-sm btn-secondary px-4"
id={props.task.id}
onClick={() =>
setData({
...data,
id: props.task.id,
content: props.task.content,
linkedPage: props.task.linkedPage,
})
}
data-toggle="modal"
data-target="#exampleModalCenterViewss"
>
Edit
</button>
Please someone explain me why the state is not updating properly.