I am using React. I also have one file that is written in jQuery. (someone wrote it, and can't re-write it now due to not having time).
In that jQuery file there's a variable var test = 2 and after some time, it changes to test = 5. I need to react in my React component when that test value changes.
So I did this in jQuery file:
window.testPromise = new Promise((res, rej) => {
setTimeout(() => {
res(test)
}, 300)
})
In my React component, I do this:
const [test, setTest] = useState(0)
(window as any).distancePromise.then((val:number) => {
setTest(val);
})
but useState somehow is broken now. It says:
This expression is not callable. Type '[number, Dispatch<SetStateAction>]' has no call signatures.
Any idea?
Try this:
window.distancePromise = () => new Promise((res, rej) => {
setTimeout(() => {
res("a value for test")
}, 300)
})
Notice that I converted it to a function.
And use it like this:
const [test, setTest] = useState(0)
useEffect(() => {
(window as any).distancePromise && (window as any).distancePromise().then((val:number) => {
setTest(val);
})
}, [])
notice the call-parenthesis ()
EDIT: I would recommend avoiding window variables in general. React has a lot of ways to avoid this, like context or using Redux or any other state management tool
EDIT2: Here is a working codeSandbox: https://codesandbox.io/s/vibrant-visvesvaraya-36fmy?file=/src/App.js
EDIT3: Never, i mean NEVER use jQuery with React.. jQuery is a DOM manipulator, exactly like React. But React is faster and better. Never use jQuery with React