allowing multiple async functions to run at once and have the ability to cancel them one at a time

I have an application where (amongst other things) a user can upload multiple files to storage. Prior to uploading, I read the file and calculate an MD5 hash. Once a user selects the file(s) for upload, I render a component (SelectedFile) for each file that was selected, passing in the file and an async progress function (which in this case will get the MD5 hash). When this component renders, the progress function starts and progress is displayed.

What I need is to allow the user to cancel the function that is running and remove the file. My implementation seems to work fine when only a single file is selected, but when multiple files are selected, the cancel functionality breaks. I end up getting the following error when I attempt to cancel one of the files (though it seems to happen inconsistently)

index.js:1 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function. at SelectedFile

I am having a lot of trouble debugging this, but I am at the point where I believe (for whatever reason) that canceling the function in one render of the SelectedFile component, is attempting to update the state of another render of this component. Here is the relevant code:

Here is the component (SelectedFile):

import { useEffect, useRef, useState } from 'react';
import { UploadBlob } from '../../apis/facade';
import {
    Card, FormLabel, LinearProgress, IconButton,
} from '@mui/material';
import { CancelOutlined } from '@mui/icons-material';

interface ISelectedFileProps {
    file: UploadBlob,
    progressFn: (
        blob: UploadBlob,
        progressCallback: (prog: number) => boolean,
        endCallback: (result: string) => void,
        onCancel: () => void,
    ) => Promise<unknown>,
    showProgress: boolean,
    allowCancel: boolean,
    startProgressFn: boolean,
    progressFinished: boolean,
    loading: boolean,
}

export function SelectedFile(props: ISelectedFileProps) {
    const {
        file, removeFile, progressFn,
        startProgressFn, progressFinished,
        showProgress, allowCancel, loading,
    } = props;

    const [progress, setProgress] = useState<number>(0);
    const [cancelProgressFn, setCancelProgressFn] = useState<boolean>(false);

    const stopProgressFn = () => {
        console.log('PRESSED CANCEL BUTTON', file.name)
        setCancelProgressFn(true);
    }

    // `progressFn` callback cannot access `cancelProgressFn` state
    const stateRef = useRef<boolean>(false);
    stateRef.current = cancelProgressFn;

    useEffect(() => {
        if (file) {
            if (progressFinished) {
                setProgress(100);
            } else {
                startProgressFn && progressFn(
                    file,
                    (prog) => {
                        setProgress(Math.round(prog * 100) || 0);
                        return stateRef.current;
                    },
                    () => {
                        setProgress(100)
                    },
                    () => {
                        console.log(`${file.name} removed`)
                    }
                );
            }
        }
    }, [file, startProgressFn, progressFinished]);

    return (
        <Card className='selected-file'>
            <span>
                {file.name}
                {showProgress &&
                    <FormLabel
                        style={{ position: 'absolute', right: 65 }}
                    >{progress}%</FormLabel>
                }
                {allowCancel &&
                    <IconButton
                        size='small'
                        color='primary'
                        onClick={stopProgressFn}
                        style={{ position: 'absolute', right: 0 }}
                        disabled={loading}
                    ><CancelOutlined fontSize="inherit" />
                    </IconButton>
                }
            </span>
            {startProgressFn && <span style={{ width: '90%' }}>
                <LinearProgress
                    variant={showProgress ? 'determinate' : 'indeterminate'}
                    value={progress}
                />
            </span>}
        </Card>
    )
}

Here is the function (calculateMD5):

const readChunked = (
    file: File,
    chunkCallback: (chunk: string, offset: number, fileSize: number) => boolean,
    endCallback: (err: DOMException | ProgressEvent<FileReader> | null) => void,
    onCancel: () => void,
) => {
    const fileSize = file.size;
    const chunkSize = 4 * 1024 * 1024; // 4MB
    let offset = 0;

    const reader = new FileReader();
    reader.onload = () => {
        if (reader.error) {
            endCallback(reader.error || {});
            return;
        } else if (reader.result) {
            const result = reader.result as string
            offset += result.length;
            const end = chunkCallback(result, offset, fileSize);
            if (offset >= fileSize) {
                endCallback(null);
                return;
            }
            if (end) {
                onCancel();
                return;
            }
        }
        readNext();
    };

    reader.onerror = (err) => endCallback(err || {});

    const readNext = () => {
        const fileSlice = file.slice(offset, offset + chunkSize);
        reader.readAsBinaryString(fileSlice);
    }
    readNext();
}

export async function calculateMD5(
    blob: UploadBlob,
    progressCallback: (prog: number) => boolean,
    endCallback: (hash: string) => void,
    onCancel: () => void,
): Promise<string> {
    return new Promise((resolve, reject) => {
        const md5 = CryptoJS.algo.MD5.create();
        readChunked(
            blob.originalFile,
            (chunk, offset, total) => {
                md5.update(CryptoJS.enc.Latin1.parse(chunk));
                return progressCallback(offset / total);
            },
            (err: DOMException | ProgressEvent<FileReader> | null) => {
                if (err) {
                    reject(err);
                } else {
                    const hash = md5.finalize();
                    const hashBase64 = hash.toString(CryptoJS.enc.Base64);
                    resolve(hashBase64);
                    endCallback(hashBase64);
                }
            },
            () => {
                onCancel();
            }
        );
    });
}

Here is how I pass it in from the parent component (SelectFiles):

export function SelectFile(props: IStepProps) {
    const {
        context: {
            supportedFiles,
            getFileHeaders,
            formatMetadata,
        },
        loading, toggleLoading,
        files, updateFiles,
        allowStepForward,
    } = props;

    /* ... */

    const updateFile = (fileToUpdate: UploadBlob) => {
        const updatedFileList = files.filter((file) => file !== fileToUpdate);
        updatedFileList.push(fileToUpdate);
        updateFiles(updatedFileList);
    }

    const onFileSelection = async (targetFiles: FileList | null) => {
        toggleLoading(true);

        try {
            const selectedFiles: UploadBlob[] = await Promise.all(
                [...(targetFiles || [])].map(async (file: File) => {
                    const extension = `.${file.name.split('.').pop()}`;
                    if (!supportedFiles.includes(extension)) {
                        throw new Error(`Supported filetypes: ${supportedFiles.join(', ')}`);
                    }
                    const fileHeaders = await getFileHeaders(file) as FileHeaders;
                    const nameWithoutExtension = file.name.split(extension)[0];
                    const metadata = formatMetadata(nameWithoutExtension, fileHeaders);

                    return {
                        originalFile: file,
                        lastModified: file.lastModified,
                        size: file.size,
                        name: file.name,
                        contentType: file.type,
                        contentMd5: '',
                        extension,
                        fileHeaders,
                        metadata,
                    }
                })
            );

            if (inputRef.current) {
                inputRef.current.value = '';
            }
            
            if (validateFileTypes(selectedFiles, supportedFiles)) {
                setErrorMessage('');
                updateFiles(selectedFiles);
                setOpenDialog(true);
            }
        } catch (e) {
            if (e instanceof Error) {
                setErrorMessage(e.message);
            }
        } finally {
            toggleLoading(false);
        }
    }

    const removeFile = (fileToRemove: UploadBlob) => {
        const updatedFileList = files.filter((file) => file !== fileToRemove);
        updateFiles(updatedFileList);
    }

    const md5ProgressFn = (
        blob: UploadBlob,
        progressCallback: (prog: number) => boolean,
        endCallback: (result: string) => void,
        onCancel: () => void,
    ) => {
        return calculateMD5(
            blob,
            (prog) => {
                return progressCallback(prog)
            },
            (hash) => {
                blob.contentMd5 = hash;
                updateFile(blob);
                endCallback(hash);
            },
            () => {
                removeFile(blob);
                onCancel();
            }
        )
    }

    /* ... */

    return (
        <div style={{ textAlign: 'center' }}>
            {errorMessage && <Alert
                className='alert select-file-error'
                severity='error'
                onClose={() => setErrorMessage('')}
            >
                <AlertTitle>{errorMessage}</AlertTitle>
            </Alert>}
            {files.length > 0 &&
                <Button
                    onClick={() => setOpenDialog(true)}
                    className='view-files'
                    disabled={loading}
                >Click here to view {files.length} selected file{files.length === 1 ? '' : 's'}
                </Button>
            }
            <div
                {...getRootProps({ className: 'action-div file-upload' })}
            >
                <div style={{ margin: 'auto' }}>
                    Drag and drop files here or
                    <Button
                        style={{ marginLeft: '5px' }}
                        disabled={loading}
                        variant='contained'
                        component='label'
                        size='small'
                    >Browse Files
                        <input
                            {...getInputProps()}
                            ref={inputRef}
                            type='file'
                            multiple={true}
                            accept={supportedFiles.join(',')}
                            onChange={({ target: { files } }) => files?.length && onFileSelection(files)}
                            hidden={true}
                        />
                    </Button>
                </div>
            </div>
            <Dialog
                open={true}
                className='file-dialog'
                style={{ visibility: openDialog && files.length ? 'visible' : 'hidden' }}
            >
                <div>
                    <IconButton
                        size='medium'
                        color='default'
                        onClick={() => setOpenDialog(false)}
                        style={{ position: 'absolute', right: 0, top: 0 }}
                        disabled={loading}
                    ><CancelOutlined fontSize="inherit" />
                    </IconButton>
                    <div className='card-container'>
                        {files.map((file, i) => (
                            <SelectedFile
                                key={i}
                                file={file}
                                removeFile={removeFile}
                                progressFn={md5ProgressFn}
                                showProgress={true}
                                allowCancel={true}
                                startProgressFn={true}
                                progressFinished={!!file.contentMd5}
                                loading={loading}
                            />
                        ))}
                    </div>
                </div>
            </Dialog>
        </div>
    )
}

Transfer Checkbox Selection to Another Php File

I need a help from you and i know, it will be basic a subject for this website members 🙂

So, i am doing a php project and created a checkbox table. This table getting datas from MySQL.

I wanna transfer of checked rows to another php file. How can i fix it?

           <form action="table3.php" method="POST" id="demo-form2" data-parsley-validate class="form-horizontal form-label-left">

            <div class="x_content">


                <div class="table-responsive">
                    <table class="table table-striped jambo_table bulk_action">
                        <thead>
                            <tr class="headings">
                                <th>
                                    <input type="checkbox" id="secim" class="flat">
                                </th>
                                <th class="column-title">ID Number </th>
                                <th class="column-title">Name and Surname </th>
                                <th class="column-title">Departman </th>
                                <th class="column-title">Starting Date </th>
                                <th class="column-title">Social Number </th>
                                </th>
                                <th class="bulk-actions" colspan="7">
                                    <a class="antoo" style="color:#fff; font-weight:500;">Bulk Actions ( <span class="action-cnt"> </span> ) <i class="fa fa-chevron-down"></i></a>
                                </th>
                            </tr>
                        </thead>

                        <tbody>
                            <?php
                            while ($personelcek = $personelsor->fetch(PDO::FETCH_ASSOC)) { ?>
                                <tr class="even pointer">
                                    <td class="a-center ">
                                        <input type="checkbox" class="flat">
                                    </td>
                                    <td name="personel_sicil"> <?php echo $personelcek['personel_sicil']; ?></td>
                                    <td name="adsoyad"><?php echo $personelcek['personel_adsoyad']; ?></td>
                                    <td name="departman"><?php echo $personelcek['personel_departman']; ?></td>
                                    <td name="giristarihi"><?php echo $personelcek['personel_giris']; ?></td>
                                    <td name="ssk"><?php echo $personelcek['personel_ssk']; ?></td>
                                    </td>
                                </tr>
                            <?php   }


                            ?>


                        </tbody>
                        <div align="right" class="col-md-6 col-sm-6 col-xs-12 col-md-offset-3">
                            <button type="submit" name="seciliform" class="btn btn-success">İzin Formu Oluştur</button>
                        </div>
                    </table>
                </div>
            </div>
    </div>
</div>

How change autoscroll direction to ltr in splide js?

I use splide js slider, and use autoscroll exstension. But I can’t find a solution to change direction from (default: right to left), to (left to right). i try this

<script>
    const splide = new Splide( '.splide', {
        type: 'loop',
        drag: false,
        focus: 'center',
        perPage: 5,
        arrows: false,
        pagination: false,
        autoScroll: {
            speed: 3,
            pauseOnHover: false,
            direction: 'ltr',
        },
        breakpoints: {
            1200: {perPage: 3},
            640: {perPage: 2},
        }
    } );

    splide.mount(window.splide.Extensions);
</script>

example link: enter link description here

Is it possible to catch a fetch request sent by a internal libary function that returns void?

For context, I’m using the react-use-intercom library function startTour(tourId: number) => void that returns void regardless if the tourId is valid or not. In the code there’s no way of checking the response status code like a typical fetch request, but in the network console, you can see that a fetch request was sent with the payload/response. Is it possible to catch that in the code still?

In the code, I only call two functions that both return void:

  const handleWhatsNewButtonClick = (): void => {
    boot();
    startTour(123456);
  };

The intercom pacakge reference: https://www.npmjs.com/package/react-use-intercom

network console

Trying to pass the values of an array to the component

I’m trying to get a single value (for that specific component) from an array.

But here is the warning message which I get: Unhandled error during execution of scheduler flush. This is likely a Vue internals bug. Please open an issue at https://new-issue.vuejs.org/?repo=vuejs/vue-next
at <SingleDrink SingleDrink= (6) [{…}, {…}, {…}, {…}, {…}, {…}]

This is how my array looks like:

data(){
    return{
    drinks: [
                    {product:"Wine", price: 149.99, url: require('../assets/images/grasevina.jpg')},
                    {product:"Beer", price: 12.99, url: require('../assets/images/corona.jpg')},
                    {product:"Vodka Smirnoff", price: 119.99, url: require('../assets/images/smirnoff.jpg')},
                    {product:"Cocktail Malibu", price: 89.99, url: require('../assets/images/malibu.jpg')},
                    {product:"Jack Daniels Honey", price: 169.99, url: require('../assets/images/jack_daniels.jpg')},
                    {product:"Strawberry liqueur", price: 149.99, url: require('../assets/images/liker-malina.jpg')}    
                ],
}
},

Same component, multiple times used – applying different css styles

I want box to get coloured but only the one i click on and the rest should have default one. Then, when i click on the next one the previous box should go back to the default color. Currently, when i click on one of them, all of the boxes get unwanted background color. I know that i basically pass “color” prop to each of them so all get coloured because of the same prop and state. But how to do it properly with only one state and without changing prop name?

const {useState} = React;

const App = () => {
  const [color, setColor] = useState("");

  const firstBox = () => {
    setColor("firstBox");
  };

  const secondBox = () => {
    setColor("secondBox");
  };

  const thirdBox = () => {
    setColor("thirdBox");
  };

  return (
    <div className="container">
      <Box setColor={firstBox} color={color} />
      <Box setColor={secondBox} color={color} />
      <Box setColor={thirdBox} color={color} />
    </div>
  );
}


const Box = ({ setColor, color }) => {
  return (
    <div
      onClick={setColor}
      className={`box  ${color === "firstBox" ? "active" : ""} 
        `}
    ></div>
  );
};


ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App/>
);
body {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.container {
  display: flex;
  gap: 2rem;
}

.box {
  width: 250px;
  height: 250px;
  background: lightblue;
}

.active {
  background: red;
}
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>

Why does the innerHTML change immediately revert when executed?

I’m a beginner working on a time conversion app. Currently, the application takes the value entered into the form and then changes the h2 element with the ID “convDate” to the entered value * 2 and then displays the result in the h2 element.

The application does run successfully, but the value immediately disappears from the screen. The changes do stick if I hold CTRL while clicking the button, while also opening the same page in a new tab. I’ve tried with both Brave and Firefox.

Can somebody explain the logic as to why this is happening? Any information is appreciated. Though, please note that I’m not looking for somebody to finish the app. I’m trying to understand concepts.

Thanks!

        <h1>64 Bit Unix Time Converter</h1>
        <form>
            <input id='unixTime' type='text'>
            <button class='button' onclick='convert()'>Convert</button>
            <h3>Value: </h3> <h2 id='convDate'></h2>
        </form> 
    
        <script>
        
        function convert(){ 
            var entValue = document.getElementById('unixTime').value; 
            var conValue = document.getElementById('convDate').value;
            document.getElementById("convDate").innerHTML = (entValue * 2);
            };
            
        </script>

MongoDB insertOne function, return result.insertedId -> stays undefined

I’m calling this function from another route to create a mongodb doc and to return the objectID from the created doc. But I’m unable to read the docID from the MongoClient.connect(...) function. Does anyone know how to return the docID in the .insertOne(...) function?

//insertOne function
module.exports.insertOne = async function (query, collectionName, callback) {
  var objectID1 = await MongoClient.connect(
    url,
    { useNewUrlParser: true, useUnifiedTopology: true },
    async (err, client) => {
      if (err) throw err;
      const db = client.db(dbname);
      let collection = db.collection(collectionName);
      var docID = await collection
        .insertOne(query)
        .then(result => {
          return result.insertedId;
        })
        .catch((err) => {
          callback(err, null);
        })
        .finally(() => {
          client.close();
        });
        return docID;
    }
  );
  return objectID1;
};

Nodejs – firebase-admin – return snapShot.data() problem

I want to pass data from /api/firestore/read.js to mainServer.js.

It does have the document, it prints, but does not return the data.

mainServer.js

app.get("/api/profile", async (req, res) => {
  const uid = req.user.uid;
  const userReader = new usersReader(uid);
  const data = await userReader.readData();
  console.log("Data", data); // data is undefined
  res.status(200).send(data);
});

read.js

const admin = require("../../firebase-config").admin;
class ReadFireDb {
  constructor(_uid) {
    this.uid = _uid;
  }

  async readData() {
    await admin
      .firestore()
      .collection("users")
      .doc(this.uid)
      .get()
      .then((snapShot) => {
        if (snapShot.exists) {
          console.log(snapShot.data()); // here i print data correctly
          return snapShot.data(); // here is the problem
        } else {
          return null;
        }
      })
      .catch((err) => console.log(err));
  }
}

module.exports = {
  ReadFireDb,
};

how is the correct way to return this data?

Am I getting a chrome security policy error because of code tokenization?

I’m trying to implement Tesseract.js into a chrome extension but I get a CSP error whenever my background script runs, which container the Tesseract calls. I tried a simpler borwser extension that runs tessercat.js as an example but I get the same CSP error. It seems to come from these code blobs things that contain the Tesseract libraries, this sort of stuff:

https://ufile.io/pk6b26qj

The chrome extension example I mentioned also has this

https://github.com/jeromewu/tesseract.js-chrome-extension

There’s even a 3MB javascript file in there.

The error I get is Content Security Policy: The page’s settings blocked the loading of a resource at blob:moz-extension://0312d6e0-72a6-49ea-8635-7468b207b6de/3090ffaf-993d-4cbf-ad80-2712368933f2 (“script-src”).

Obviously the alpha-numeric url part is different for the github extension, but same deal

Here’s my background script:


chrome.tabs.onActivated.addListener((tabId, changeInfo, tab) => {

    chrome.tabs.captureVisibleTab({format: "png"}, function(imageUri){
        chrome.storage.local.set({image_uri: imageUri}); 

        Tesseract.recognize(
            imageUri,
            "eng"
        )
            .catch(err => console.error(err))
            .then(({data: {text}}) => {
                console.log(text)
            })  ;  
    });
});

and my manifest:

    "manifest_version": 2, 
    "name": "Name2Clip",
    "version": "0.1.0",
    "description": "things",
    "icons": {
        "128": "assets/global-icon128.png",
        "48": "assets/global-icon48.png",
        "16": "assets/global-icon16.png"
    },
    "browser_action": {
        "default_icon": "assets/global-icon16.png",
        "default_popup": "popup.html"
    },
    "background": {
        "scripts": [
            "scripts/main.js"
        ],
        "persistent": false
    },
    "permissions": [
        "<all_urls>",
        "activeTab",
        "unlimitedStorage",
        "storage"
    ]
}

I tried toggling off the security.csp.enable policy inside about:config but I still get the CSP error.

I’m running this on firefox 102.0.1

Signing a http request using fetch does not match the signature on aws

I am trying to make a request to a resource in API gateway which currently has the auth set to IAM and I am trying to make the request using the fetch library.

I am able to make the request in Postman with no issues passing in my keys. However through my code I get an error stating

The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method

import dayjs from 'dayjs';
import localizedFormat from 'dayjs/plugin/localizedFormat';
import advancedFormat from 'dayjs/plugin/advancedFormat';
import utc from 'dayjs/plugin/utc';
import crypto from 'crypto-js';

dayjs.extend(utc);
dayjs.extend(localizedFormat);
dayjs.extend(advancedFormat);

const awsDateStamp = dayjs().utc().format('YYYYMMDD[T]HHmmss[Z]');
const dateStamp = dayjs.utc().format('YYYYMMDD');

function getSignatureKey(
  key: string,
  dateStampx: string | crypto.lib.WordArray,
  regionName: string | crypto.lib.WordArray,
  serviceName: string | crypto.lib.WordArray,
) {
  const kDate = crypto.HmacSHA256(dateStampx, `AWS4${key}`);
  const kRegion = crypto.HmacSHA256(regionName, kDate);
  const kService = crypto.HmacSHA256(serviceName, kRegion);
  const kSigning = crypto.HmacSHA256('aws4_request', kService);
  return kSigning;
}

const getCreditOffers = async (productId: string, price: number) => {
  let creditOffers = null;

  try {
    if (!productId) throw Error('Product Id was not provided');

    if (!price) throw Error('Price was not provided');

    const signedKey = getSignatureKey(
      'SecretKey',
      dateStamp,
      'eu-west-1',
      'execute-api',
    );

    const myHeaders = new Headers();
    myHeaders.append('Accept', 'application/vnd.api+json');
    myHeaders.append(
      'X-Amz-Security-Token',
      'Session Token',
    );
    myHeaders.append(
      'Authorization',
      `AWS4-HMAC-SHA256 Credential= AccessKey/${dateStamp}/eu-west-1/execute-api/aws4_request, SignedHeaders=accept;host;x-amz-date;x-amz-security-token, Signature=${signedKey}`,
    );

    myHeaders.append('x-debug-enabled', 'true');
    myHeaders.append('X-Amz-Date', awsDateStamp);

    const response = await fetch(
      'https://nonprd-api.dcx.mycooldomain.com/domain-offers/dev1/offers/product/2343?site=SITE&price=1200',
      { headers: myHeaders, redirect: 'follow' },
    );

    response
      .text()
      .then((res) => {
        console.log('no issues', res);
      })
      .catch((err) => {
        console.error('error', err);
      });

    if (!response.ok) {
      throw Error('Could not retrieve credit offer');
    }

    const { data } = await response.json();

    creditOffers = creditOfferAdaptor.fromApi(data.attributes);
  } catch (error) {
    console.error(error.message);
  }

  return creditOffers;
};

export default {
  getCreditOffers,
};

Not sure what I am doing wrong, but the error I get back

{
    "errors": [{
                "code": "BadRequest",
                "title": "BAD_REQUEST",
                "detail": "The request signature we calculated does not match the signature you provided. Check your AWS Secret Access Key and signing method. Consult the service documentation for details.

                The Canonical String
                for this request should have been 'GET /
                domain - creditoffers / dev1 / creditoffers / product / 1182412316
                price = 1200 & site = SITE
                accept: application / vnd.api + json
                host: nonprd - api.dcx.mycooldomain.com
                x - amz - date: 20220719 T144918Z
                x - amz - security - token: mysessionToken

                accept;host;x - amz - date;x - amz - security - token
                e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 '

                The String - to - Sign should have been 'AWS4-HMAC-SHA256
                20220719 T144918Z
                20220719 / eu - west - 1 / execute - api / aws4_request
                75 de4bb8eafc2c39183553bbedd35b8af41804aae50e2864e18b3a6749398dcb '
                ", "
                meta ": { "
                correlationId ": "
                Please check the correlation id in the response header " } } ], "
                statusCode ": 400 }

Any help would be appreciated

How to test curl in postman

Everyone.
I am going to test api that is consisted of curl.
But it is not working in the postman.
If you have experience in this field, Please help me.
This is Curl request.

curl -X POST -H "Authorization: Basic bGFyc3ZpbmRlcjpHdWxlR3VtbWlzdMO4dmxlcg==" -d '
{
"to":"4522334488", "message": "This is the message text body", "from": "Compaya", "timestamp": 1474970400
}
' "https://api.cpsms.dk/v2/send"

And if possible, please help me to convert this to axios command.
Thank you in advance.

How to not let a timer stop in nextJS when idle

Basically, I created a simple timer app with Next

https://sitstandtimer.vercel.app/

and I want it to just stay counting even if I’m not on the browser window. When I go to another window for about 5 minutes it stops counting, which is odd behavior. Here’s the code for the Timer:

const useTimer = (initialState = 0) => {
    const [timer, setTimer] = useState(initialState)
    const [isActive, setIsActive] = useState(false)
    const [isPaused, setIsPaused] = useState(false)
    const countRef = useRef(null)
  
    const handleStart = () => {
      setIsActive(true)
      setIsPaused(true)
      countRef.current = setInterval(() => {
        setTimer((timer) => timer + 1)
      }, 1000)
    }
  
    const handlePause = () => {
      clearInterval(countRef.current)
      setIsPaused(false)
    }
  
    const handleResume = () => {
      setIsPaused(true)
      countRef.current = setInterval(() => {
        setTimer((timer) => timer + 1)
      }, 1000)
    }
  
    const handleReset = () => {
      clearInterval(countRef.current)
      setIsActive(false)
      setIsPaused(false)
      setTimer(0)
    }
  
    return { timer, isActive, isPaused, handleStart, handlePause, handleResume, handleReset, setTimer }
  }

POST http://localhost:3000/api/v1/register 500 (Internal Server Error)

When Cloudinary is not included my Code runs fine on Postman. As I include Cloudinary to in register route to add photos to account, I am getting this error

userAction.jsx

export const register = (userData) => async (dispatch) => {
    try {
      dispatch({ type: REGISTER_USER_REQUEST });
  
      const config = { headers: { "Content-Type": "multipart/form-data" } };
  
      const { data } = await axios.post(`/api/v1/register`, userData, config);
  
      dispatch({ type: REGISTER_USER_SUCCESS, payload: data.user });
    } catch (error) {
      dispatch({
        type: REGISTER_USER_FAIL,
        payload: error.response.data.message,
      });
    }
  };

LoginSignup.jsx

import React, {Fragment,useRef,useState, useEffect} from "react";
import "./LoginSignUp.css";
import Loader from "../layout/Loader/Loader";
import { Link, useNavigate } from "react-router-dom";
import LockOpenIcon from '@mui/icons-material/LockOpen';
import EmailIcon from '@mui/icons-material/Email';
import PersonIcon from '@mui/icons-material/Person';
import img from "../../images/Profile.png";
import {useSelector, useDispatch} from "react-redux";
import {clearErrors, login , register} from "../../actions/userAction.jsx";
import {useAlert} from "react-alert";
 

export default function LoginSignUp(){

    const dispatch = useDispatch();
    const alert = useAlert();
    const navigate = useNavigate();


    const {error,loading,isAuthenticated} = useSelector((state)=>state.user);

    const loginTab=useRef(null);
    const registerTab = useRef(null);
    const switcherTab = useRef(null);

    const [loginEmail,setLoginEmail] = useState("");
    const [loginPassword,setLoginPassword] = useState("");

    const [user,setUser] = useState({
        name:"",
        email:"",
        password:"",
    });

    const {name,email,password} = user;

    const [avatar, setAvatar] = useState(img);
    const [avatarPreview, setAvatarPreview] = useState(img);

    function loginSubmit(e){
        e.preventDefault();
        dispatch((login(loginEmail,loginPassword)));
    }

    function registerSubmit(e){
        e.preventDefault();
        
        const myForm = new FormData();

        myForm.set("name",name);
        myForm.set("email",email);
        myForm.set("password",password);
        myForm.set("avatar",avatar);

        dispatch(register(myForm));
    }

    function registerDataChange(e){
        if(e.target.name==="avatar"){
            const reader = new FileReader();
            reader.onload = ()=>{
                if(reader.readyState===2){
                    setAvatarPreview(reader.result);
                    setAvatar(reader.result);
                }
            };

            reader.readAsDataURL(e.target.files[0]);
        } else {
            setUser({...user, [e.target.name]:e.target.value});
        }
    }

    useEffect(()=>{
        if(error){
            alert.error(error);
            dispatch(clearErrors());
        }
        if(isAuthenticated){
            navigate(`/account`);
        }
    },[dispatch,error,alert,isAuthenticated,navigate]);

    const switchTabs = (e, tab) => {
        if (tab === "login") {
          switcherTab.current.classList.add("shiftToNeutral");
          switcherTab.current.classList.remove("shiftToRight");
    
          registerTab.current.classList.remove("shiftToNeutralForm");
          loginTab.current.classList.remove("shiftToLeft");
        }
        if (tab === "register") {
          switcherTab.current.classList.add("shiftToRight");
          switcherTab.current.classList.remove("shiftToNeutral");
    
          registerTab.current.classList.add("shiftToNeutralForm");
          loginTab.current.classList.add("shiftToLeft");
        }
      };

    return(
        <Fragment>
            {loading ? <Loader/> : (
                <Fragment>
                    <div className="LoginSignUpContainer">
                        <div className="LoginSignUpBox">
                            <div>
                                <div className="login_signUp_toggle">
                                    <p onClick={(e)=>switchTabs(e,"login")}>Login</p>
                                    <p onClick={(e)=>switchTabs(e,"register")}>Register</p>
                                </div>
                                <button ref={switcherTab}></button>
                            </div>
                            <form
                                className="signUpForm"
                                ref={registerTab}
                                encType="multipart/form-data"
                                onSubmit={registerSubmit}
                            >
                                <div className="signUpName">
                                <PersonIcon />
                                <input
                                    type="text"
                                    placeholder="Name"
                                    required
                                    name="name"
                                    value={name}
                                    onChange={registerDataChange}
                                />
                                </div>
                                <div className="signUpEmail">
                                <EmailIcon />
                                <input
                                    type="email"
                                    placeholder="Email"
                                    required
                                    name="email"
                                    value={email}
                                    onChange={registerDataChange}
                                />
                                </div>
                                <div className="signUpPassword">
                                <LockOpenIcon />
                                <input
                                    type="password"
                                    placeholder="Password"
                                    required
                                    name="password"
                                    value={password}
                                    onChange={registerDataChange}
                                />
                                </div>

                                <div id="registerImage">
                                <img src={avatarPreview} alt="Avatar Preview" />
                                <input
                                    type="file"
                                    name="avatar"
                                    accept="image/*"
                                    onChange={registerDataChange}
                                />
                                </div>
                                <input type="submit" value="Register" className="signUpBtn" />
                            </form>
                        </div>
                    </div>
                </Fragment>
            )}
        </Fragment>
    );
}

userController.jsx

exports.RegisterUser = catchAsyncErrors( async (req,res,next)=>{

    // const myCloud = await cloudinary.v2.uploader.upload(req.body.avatar,{
    //   folder: "avatars",
    //   width: 150,
    //   crop:"scale",
    // });

    const {name,email,password} = req.body;

    const user = await User.create({
        name,
        email,
        password,
        avatar: {
            public_id:"myCloud.public_id",
            url: "myCloud.secure_url",
        }
    });

    sendToken(user,201,res);
});
  1. I have an id on Cloudinary and imported its Name, API_KEY, API_SECRET
  2. Backend code works well on postman without Cloudinary