Work with heavy / time consuming functions in React (Node.JS)

Asked

Viewed 52 times

1

I have an React project where when the user opens a page, the app starts creating a 2048 RSA key pair. How do I ensure that the page does not "lock", IE, it is in the background and when the key is created I inform the user that everything is ready.

const navigate = useNavigate();
        const [keyStatus, setKeyStatus] = useState('Em processamento... (É normal que a pagina parece ter crashado! Por favor espere!)');
        const [pubKey, setPubKey] = useState('');
        const [privKey, setPrivKey] = useState('');
        const [genState, setGenState] = useState(0);
        function exitModal(){
            modal.setModal(true);
        }
        async function downloadPrivKey() {
            if(genState === 1){
                await api.post('/savePublicKey', {
                    publicKey: pubKey
                }).then(function(response){
                    fileDownload(privKey, 'private.key', 'text/plain');
                    setGenState(2);
                }).catch(function (){
                    navigate('/', { replace: true });
                });
            }
        }
        useEffect(() => {
      async function startGenerationKeys() {
        const keysWorker = new Worker();
        keysWorker.postMessage("start");
        keysWorker.onmessage = (e) => {
            setPrivKey(e.data.privKey);
            setPubKey(e.data.pubKey);
            setKeyStatus('Pronta para download!');
            setGenState(1);
        };
    }
    startGenerationKeys();
        }, []);

Webworker:

    import NodeRSA from 'node-rsa';

    export default onmessage = function() {
        const keysPair = new NodeRSA({ b: 4096 });
        const pubKey = keysPair.exportKey('public').replace(/(\r\n|\n|\r)/gm,"");
        const privKey = keysPair.exportKey('private');
        postMessage({
            pubKey,
            privKey
        });
    }
  • await new NodeRSA({ b: 4096 }); It doesn’t make sense here. Builders are not async.

  • Web Workers could be an output, delegating the task to a separate thread. Take a search in that direction.

  • I tried to put a webWorker. the page continues to hang, including a warning "Page without response" from Google Chrome.

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.