Can I call a variable whose path is in /public/assets/js in my React project within useEffect() in React views?
For example, can I use jsVal like below?
useEffect(() => {
const existingScript = jsVal.getSum();
...
}
The reason why I am curious is because, when the screen made with React is turned on with chrome, jsVal is not 'jsVal is not defined' in the Console Tab of Developer Tools.
However, in useEffect, jsVal comes out as 'can not find Name', so I leave a question.
Add The location where jsVal is defined is /public/assets/js/test.js.
If your value is exposed in some way through global or window then yes, you can access it in React!
i.e.
// public/assets/file.js
window.jsVal = {
getSum(a, b) { return a + b; }
}
// In case of typescript, add an ambient declaration too!
declare global {
interface Window {
jsVal: {
getSum(a: number, b: number): number;
}
}
}
// React app (make sure file.js is included before React in index.html)
const MyComponent = () => {
const [val, setVal] = useState(null);
useEffect(
() => {
setVal(window.jsVal.getSum(10, 32)); // 42
},
[window.jsVal, setVal]
);
return null;
}
I assume jsVal is a global service/variable ? If so.
Everything of React is javascript. You can think React is a global variable.
React.render(<App />, el)
So in general, it depends on if jsVal is defined early or later than render. However useEffect is also a bit special. It actually fires in another Javascript task/tick, similar to setTimeout or an API, so its execution is deferred in async way.