0

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?

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

1. same problem, it didn't help. 2. how can I use context or redux ? the value is in Jquery's file
There is no such thing as a jQuery file.. it is simply a JS file. I added a codesandbox that proves it works.. On how to use Context or Redux I can't explain it with a comment or SO post.. You need to learn it yourself, there are hundreds of tutorials online.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.