Home > front end >  Unhandled Rejection (TypeError): when I add Redux connect mapDispatchToProps
Unhandled Rejection (TypeError): when I add Redux connect mapDispatchToProps

Time:11-21

When I remove Redux connect mapDispatchToProps then it's working ok so what have I missed.

When I export like so I get no error

export default HandleFiles;

When I export like so I get Unhandled Rejection (TypeError):

export default connect(null, mapDispatchToProps)(HandleFiles);

I can't see why???

Here's the error and you see it's in the FilePicker.jsx

enter image description here

Here's FilePicker.jsx

import React from 'react';
import { compose } from 'recompose';
import { useDispatch, connect } from 'react-redux';
import Button from '@material-ui/core/Button';
import Dropzone from './Dropzone';
import { setNewFiles } from '../../../../../redux/filesData/files.actions';
import {
    enqueueSnackbar as enqueueSnackbarAction,
    closeSnackbar as closeSnackbarAction,
} from '../../../../../redux/snackbar/snack.action';
import * as SNACK_BAR from '../../../../../constants/snackbar';
import HandleFiles from './HandleFiles';

const FilePicker = ({ setNewFileForValidation }) => {
    const dispatch = useDispatch();
    const enqueueSnackbar = (...args) => dispatch(enqueueSnackbarAction(...args));
    const closeSnackbar = (...args) => dispatch(closeSnackbarAction(...args));


    const readAllFiles = async AllFiles => {
        const results = await Promise.all(
            AllFiles.map(async file => {
                const sha = await HandleFiles(file );
                const file2 = new File([file], file.name, { type: file.type });
                file2.sha = sha;
                return file2;
            }),
        );
        console.log('results', results);
        return results;
    };

    function onDrop(acceptedFiles, rejectedFiles) {
        readAllFiles(acceptedFiles).then(result => {
            // const res = removeUnwantedFiles(result);
            setNewFileForValidation(result);
        });
    }
    return <Dropzone onDrop={onDrop} />;
};

const mapDispatchToProps = dispatch => ({
    setNewFileForValidation: newFiles => dispatch(setNewFiles(newFiles)),
});

const enhance = compose(connect(null, mapDispatchToProps));
export default enhance(FilePicker);

Here's HandleFiles.jsx

import CryptoJS from 'crypto-js';
import { connect } from 'react-redux';
import {
    enqueueSnackbar as enqueueSnackbarAction,
    SnackbarProgress as SnackbarProgressAction,
} from '../../../../../redux/snackbar/snack.action';

/**
 * Order file chunks with a time-shifting technique:
 * https://medium.com/@0xVaccaro/hashing--file-with-filereader-js-e0a5c898fc98
 * https://github.com/lvaccaro/hashfilereader
 * @param {File} item
 * @param {function} dispatch
 */
const HandleFiles = item => {
// const HandleFiles = ({ item, setSnackbarAction, setEnqueueSnackbarAction }) => {
    let chunkReorder = 0;
    let chunkTotal = 0;
    let lastOffset = 0;
    const chunkSize = 1024 * 1024; // bytes
    // const enqueueSnackbar = (...args) => dispatch(enqueueSnackbarAction(...args));
    function HumanFileSize(bytes, si) {
        const thresh = si ? 1000 : 1024;
        let bytez = bytes;

        if (Math.abs(bytez) < thresh) {
            return `${bytez} B`;
        }
        const units = si
            ? ['kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
            : ['KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'];
        let u = -1;
        do {
            bytez /= thresh;
            u -= 1;
        } while (Math.abs(bytez) >= thresh && u < units.length - 1);
        return `${bytez.toFixed(1)} ${units[u]}`;
    }

    function callbackRead(obj, file, evt, callbackProgress, callbackFinal) {
        CallbackReadWaiting(obj, file, evt, callbackProgress, callbackFinal);
    }

    // time reordering
    function CallbackReadWaiting(reader, theFile, evt, callbackProgress, callbackFinal) {
        const timeout = 10; // millisec

        if (lastOffset === reader.offset) {
            // console.log('[', reader.size, ']', reader.offset, '->', reader.offset   reader.size, '');
            lastOffset = reader.offset   reader.size;
            callbackProgress(evt.target.result);
            if (reader.offset   reader.size >= theFile.size) {
                lastOffset = 0;
                callbackFinal();
            }
            chunkTotal  = 1;
        } else {
            // console.log('[', reader.size, ']', reader.offset, '->', reader.offset   reader.size, 'wait');
            setTimeout(function f() {
                CallbackReadWaiting(reader, theFile, evt, callbackProgress, callbackFinal);
            }, timeout);
            chunkReorder  = 1;
        }
    }

    function Loading(theFile, callbackProgress, callbackFinal) {
        // var chunkSize  = 1024*1024; // bytes
        let offset = 0;
        const size = chunkSize;
        let partial;
        let index = 0;
        if (theFile.size === 0) {
            callbackFinal();
        }
        while (offset < theFile.size) {
            partial = theFile.slice(offset, offset   size);
            const reader = new FileReader();
            reader.size = chunkSize;
            reader.offset = offset;
            reader.index = index;
            reader.onload = function f(evt) {
                callbackRead(this, theFile, evt, callbackProgress, callbackFinal);
            };
            reader.readAsArrayBuffer(partial);
            offset  = chunkSize;
            index  = 1;
        }
    }

    return new Promise((resolve, reject) => {
        // var file = this.files[0];
        const SHA256 = CryptoJS.algo.SHA256.create();
        let counter = 0;
        const self = this;
        const timeStart = new Date().getTime();
        let timeEnd = 0;
        console.log('timeStart ', new Date(timeStart));
        console.log('humanFileSize ', HumanFileSize(item.size, true));
        Loading(
            item,
            function d(data) {
                const wordBuffer = CryptoJS.lib.WordArray.create(data);
                SHA256.update(wordBuffer);
                counter  = data.byteLength;
                console.log(`${((counter / item.size) * 100).toFixed(0)}%`);

            },
            function v(data) {
                const ff = SHA256.finalize().toString();
                console.log('#hash ', ff);
                resolve(ff);
            },

        );
    });
};

const mapDispatchToProps = dispatch => ({
    setSnackbarAction: value => dispatch(SnackbarProgressAction(value)),
    setEnqueueSnackbarAction: value => dispatch(enqueueSnackbarAction(value)),
});

export default connect(null, mapDispatchToProps)(HandleFiles);

CodePudding user response:

You are trying to connect HandleFiles which is not a react component but just a function (does not return jsx). The connect function from react-redux can only work for react components and thus you get the error. You can try reading from redux only from FilePicker component and pass it on HandleFiles function as call parameters

  • Related