I am trying to access the value of current scroll position inside a Function. The two parameters are working fine and can be assessed, but when I am using the scrollPos state, it says undefined but I can see its actual value outside the function. How can I access it inside of the function. I am using react-dnd for implementing drag n drop and react-pdf for showing react pdf
import { useDrag, useDrop } from 'react-dnd';
import { Document, Page } from 'react-pdf/dist/esm/entry.webpack';
const [scrollPos, setScroll] = useState();
const containerRef = useRef();
const [addedFields, setAddedFields] = useState([]);
const handleScroll = (event) => {
const { scrollHeight, scrollTop, clientHeight } = event.target;
const scroll = scrollHeight - scrollTop - clientHeight;
const intScroll = parseInt(scroll, 10);
setScroll(1470 - intScroll);
};
const [, drop] = useDrop(() => ({
accept: 'card',
drop: (item, monitor) => {
const offset = monitor.getSourceClientOffset();
if (offset && containerRef.current) {
const dropTarget = containerRef.current.getBoundingClientRect();
markField(item, {
x: offset.x - dropTarget.left,
y: offset.y - dropTarget.top,
});
}
},
collect: (monitor) => ({
isOver: monitor.isOver(),
}),
}));
console.log('Outer', scrollPos); // someValue
const markField = (item, cordinates) => {
console.log('Inner', scrollPos); // undefined
const fieldDetails = {
url: item.url,
id: item.id + 1,
cordinates: {
x: 490 + cordinates.x,
y: 665 + cordinates.y + window.scrollY,
},
};
// Set fields
setAddedFields((state) => ([...state, fieldDetails]));
};
const renderDoc = () => (
<div style={{ overflowY: 'scroll' }} onScroll={handleScroll}>
<Grid container justify="center" style={{ position: 'relative' }}>
<Document
file={acceptedFiles[0]}
onLoadSuccess={onDocumentLoadSuccess}
renderMode="canvas"
>
<Grid ref={drop} container style={{ height: '1080px', position: 'relative' }} justify="center">
{[...Array(numPages).keys()]
.map((x, i) => i + 1)
.map((page) => (
<Page
key={page}
renderAnnotationLayer
renderInteractiveForms
pageNumber={page}
width={windowWidth * 0.6}
scale={1}
/>
))}
{addedFields.length > 0 && addedFields.map((field) => ([
<DraggableField id={field.id} url={field.url} cordinates={field.cordinates} />,
]))}
</Grid>
</Document>
</Grid>
</div>);