so i have a react website. I have a script file for animations/transitions called AppHomeScript.js that I import in the index.html with a script tag at the end:
<script src="./scripts/AppHomeScript.js" defer ></script>
the script file also has :
window.onload = () => {
console.log("LOADING SCRIPTS");
const homeButton = document.querySelector(".home-btn");
console.log("HOME BTN: ", homeButton);
const loginPage = document.querySelector(".login-page");
const loginButton = document.querySelector(".login-btn");
const registerButton = document.querySelector(".register-btn");
const registerPage = document.querySelector(".register-page")
const mainTexts = document.querySelector(".main-texts");
const hamburger = document.querySelector(".hamburger");
})
to make sure that it only runs after the components have finished loading. The problem is, in my local computer. the animations work fine in my chrome and operaGX browser. but it does not work on my
internet explorer,chrome's incognito mode, and my android phone's chrome. I also already hosted it in netlify, and I asked my friend if the animations work on their browser, but it does not. a part of the file console logs one of the documents it is trying to get, and it logs null. this gives me the idea that the script is being run even though the components haven't finished rendering.
I am using ES6 for the scripts, if you want to see the whole Script file, it is here:
https://github.com/BjornPython/locate-martial-arts-client/blob/main/public/scripts/AppHomeScript.js
here is the live demo of the app hosted in netlify:
https://poetic-capybara-66732c.netlify.app/
i tried different ways of importing the script file. like using useEffect and ComponentDidMount, or removing the
window.onload = () => {}
when i remove window.onload, the script runs before the components run, and it does not work on any of the browsers.
EDIT // EDIT // EDIT // EDIT // EDIT // EDIT // EDIT
I found a fix, but i'm not sure if this is the best way to deal with this problem.
I added a setTimeout function inside my window.onload.
window.onload = () => {
setTimeout(() => {
// MY CODE HERE // MY CODE HERE
}, 500);
}
If you have a better way of solving this problem, I would greatly appreciate it!
There are a few reasons why your JavaScript code may be running before your components have finished rendering in React:
Execution order: JavaScript code is executed in the order it is included in your HTML file. If your JavaScript code is included before your React components, it will execute before the components can render.
Asynchronous rendering: React components can be rendered asynchronously, which means that the component may not finish rendering before the JavaScript code runs. This can happen if your component makes an API call or performs other asynchronous operations.
State updates: React components can also update their state asynchronously, which means that changes to the state may not be reflected in the component before your JavaScript code runs.
To ensure that your JavaScript code runs after your React components have finished rendering, you can use the componentDidMount lifecycle method. This method is called after the component has finished rendering, so you can be sure that your component is ready before running any JavaScript code. Alternatively, you can use React's built-in useEffect hook to run code after the component has finished rendering.
Related
I implemented the API to run when the screen is accessed using useEffect in Next.js
The code is simply written as below.
When I first access, the API of the useEffect runs normally.
However, if I go to another screen and then access the screen again, useEffect does not work.
This is the same for useEffect on other screens.
Can I run useEffect every time I access the screen?
Currently, the dependency is set to [], but if [] is removed at all, the application stops.
Which solution will help me?
useEffect(() => {
dispatch(getCartAction());
dispatch(getWishlistAction());
dispatch(getProductsAction());
}, []);
No matter how much I look, I can't find a problem like this.
I have an electron app, it goes through a couple of files before creating the first window. But when it gets to the file that should create the window I checked and it is simply never ready. I am getting the error for creating a window before the app is ready but it's not a matter of time it really is just never ready.
I even put a while loop to while the app isn't ready and it never ends, I then moved it to the very first line of the first file (after requiring the app module) and it still got stuck and I have no idea why.
There really isn't any code to see here, it just the first line of the program there is nothing in the code that can affect it
The way you're checking the app readiness inside the loop isn't required at all. You can use the ready event as given in official docs or you can use the whenReady method which returns a promise to check the app is ready.
...
app.on('ready', () => {
...
...
});
//or
app.whenReady().then(() => {
...
});
Here is the example of using the whenReady.
The test in the code below is a very common pattern I have seen both online and at a company I interned at:
import React from 'react';
import { shallow } from 'enzyme';
import Button from './Button';
describe('Test Button component', () => {
it('Test click event', () => {
const mockCallBack = jest.fn();
const button = shallow((<Button onClick={mockCallBack}>Ok!</Button>));
button.find('button').simulate('click');
expect(mockCallBack.mock.calls.length).toEqual(1);
});
});
What I don't understand is why bother writing this test? If a component has an onClick property, and onClick is supplied a callback, of course clicking that component will result in the callback being called. When would this ever fail? What am I not considering here?
Actually this test testing two things:
Button calls provided onClick handler, if your teammate perform some refactoring in Button component and forgot to provide onClick function to native button element this test will fail. This kind of problem will be discovered in PR when someone review changes or in testing but none of this two guarantees you that broken button wont appear in production.
Button renders, i.e. some library that you use to style that Button is broken, it is common case in javascript world. then/is-promise 1-liner library with 11+ million usages has been broken today. So if you test code it will fall locally or on CI before you merge it.
But with shallow rendering second case wont work as expected here because it doesn't render all components in the react tree with running all lifecycle hooks, it is considered as bad practice in testing, you can checkout post by Kent C Dodds Why I never use shallow rendering for more details.
It is important part of testing culture to test everything, the code is not working until you test it, if your code is simple, the test will be simple too. It is good code. If your code is entangled and complicated most likely you won't be able to write a test for your code at all. You will have to refactor it to make it testable and simple. It is praiseworthy that you are thinking about the meaning of the test, sometimes tests can be useless but your example is not.
I am using Headless JS in react native to create background service. My requirement is to create a service which will be invoked from MainActivity (For example on click of a button) and continue to execute even after the App goes to background. I could manage to create the service with Headless JS and invoke on button click. For simplicity I will explain with simple code
MyTask.js
module.exports = async () => {
console.log("I am called from java service");
for(var i=0; i<1000000;i++){
console.log("I am called from for loop"+i);
}
};
When using the above code, even after the app goes to background the for loop continues execution till i reaches 999999 also I am able to see the log message in console.
But my actual Task contains some async functions. For example when I use the following code in my task, it fails to print when the app goes to background
module.exports = async () => {
console.log("I am called from java service");
setInterval(() => {
console.log("I am called from java service inside setInterval");
}, 100);
};
The above code is supposed to print the log message continuously in 100 ms intervals. But the moment the app goes to background it stops printing. Again when the app resumes, it start printing again.
Can someone help on this?
My guess is that your activity is paused once your async headless task is over (from the caller perspective), this is what RN documentation suggests :
You can do anything in your task such as network requests, timers and
so on, as long as it doesn't touch UI. Once your task completes (i.e.
the promise is resolved), React Native will go into "paused" mode
(unless there are other tasks running, or there is a foreground app).
Although it's unclear, as you might think that JS timers - like setInterval would keep your code running... They won't.
The solution implied by RN doc is to implement a native service - for example a native timer instead of a JS one - which is basically what react-native-background-timer does...
EDIT
Regarding foreground execution, by default, headlessJS tasks are not allowed in foreground and will raise an error.
In our Android app, I initialize the React Native JS code as soon as possible, because I have some JS code running in the background, even when no React Native views are currently visible. I do this by calling ReactInstanceManager#createReactContextInBackground().
This works, and the JS code gets initialized, but it appears I cannot call any Java methods annotated with #ReactMethod until I have actually opened a React Native view that calls ReactRootView#startReactApplication(). If I attempt to call any native methods before that, nothing happens, but it seems the calls get added to a queue and then eventually get picked up when the React view opens.
It appears the same thing goes for timers set with setTimeout(). They just don't get called when no view is open yet. So it seems the JS gets evaluated, but then the JS engine isn't "running" yet.
How can I make sure the engine is properly running before opening any React views?
Let your first RN View call a #ReactMethod that will set a flag in Java. Have your Java code not execute anything until the flag is set.