sandinmyjoints / use-async-queue

React Hook implementing a queue with optional concurrency limit.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error: Invalid hook call. Hooks can only be called inside of the body of a function component.

thehardikmodha opened this issue · comments

I'm doing React + Bootstrap + AdminLte 3. And I have used use-async-queue package. I'm getting this error.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app

LotteryScan src/pages/daily_report/lottery/LotteryScan.js:87

This is LotteryScan code.

import React, {useCallback, useEffect, useRef, useState} from "react";
import useAsyncQueue from "use-async-queue";
import {setDailyLotteryScans, setDailyScanTotal} from "../../../store/reducers/App";
import Store from "../../../store/index"
import {responseValidate} from "../../../utils/functions";
import {isNumeric} from "rxjs/internal-compatibility";
import {connect} from "react-redux";
import {api_version} from "../../../settings";

const LotteryScan = ({Key, title = null, shift, store, daily_scan}) => {

    const scanCodeInput = useRef();
    const [totalSold, setTotalSold] = useState(0);
    const [itemId, setItemId] = useState(1);
    const [cache, setCache] = useState({});
    const [numBatchesFinished, setNumBatchesFinished] = useState(0);
    const [highlight, setHighlight] = useState(false);
    const [changeApiTimer, setChangeApiTimer] = useState(0);

    const highlightFirstElement = () => {
        if (changeApiTimer) clearTimeout(changeApiTimer);
        setHighlight(true);
        setChangeApiTimer(setTimeout(() => setHighlight(false), 500));
    }

    useEffect(() => {
        if (daily_scan instanceof Array) {
            const sumNetTaxes = daily_scan.reduce(((previousValue, currentValue) => {
                let quantity =
                    (currentValue.ticket_number !== undefined ? (currentValue.ticket_number + 1) : (currentValue.count - 1))
                    - (currentValue.current_ticket_number !== undefined ? currentValue.current_ticket_number : 0);
                quantity = !isNaN(quantity) ? quantity : 0;
                return previousValue + (currentValue.price !== undefined ? (currentValue.price * quantity) : 0)
            }), 0);
            setTotalSold(sumNetTaxes);
            Store.dispatch(setDailyScanTotal(Key, sumNetTaxes))
        }
    }, [daily_scan]);

    const inflight = useCallback(({id}) => {
        setCache(c => {
            return {...c, [id]: "inflight"};
        });
    }, [setCache]);

    const done = useCallback(({result}) => {
            result
                .then(res => responseValidate(res))
                .then(result => {
                    if (result.status === true) {
                        // Store.dispatch(setSnackbarMessage(SnackBarStatus.success, result.message, 2000))
                        if (daily_scan !== null) {
                            const objectIndex = daily_scan.findIndex(function (object) {
                                return object.store_lottery_inventory_id === result.data.store_lottery_inventory_id;
                            });
                            let DailyScan = [...daily_scan];
                            if (objectIndex !== -1) {
                                DailyScan[objectIndex].current_ticket_number = result.data.ticket_number;
                                DailyScan.splice(0, 0, DailyScan.splice(objectIndex, 1)[0]);
                                Store.dispatch(setDailyLotteryScans(DailyScan));
                                highlightFirstElement();
                            } else {
                                const DailyScanObject = {...result.data};
                                DailyScanObject.ticket_number = undefined;
                                DailyScanObject.current_ticket_number = result.data.ticket_number;
                                DailyScan.splice(0, 0, DailyScanObject);
                                Store.dispatch(setDailyLotteryScans(DailyScan));
                                highlightFirstElement();
                            }
                        } else {
                            const DailyScan = [];
                            DailyScan.push(result.data)
                            Store.dispatch(setDailyLotteryScans(DailyScan));
                            highlightFirstElement();
                        }
                    } else {
                        // Store.dispatch(setSnackbarMessage(SnackBarStatus.error, result.message, 2000))
                    }
                });
        },
        [daily_scan, highlightFirstElement]);

    const drain = useCallback(() => setNumBatchesFinished(n => n + 1), [
        setNumBatchesFinished
    ]);

    const queue = useAsyncQueue({
        concurrency: 1,
        inflight,
        drain,
        done
    });

    const callApi = (code) => {
        const task = {
            id: itemId,
            task: () =>
                new Promise(resolve => {
                    setTimeout(() => resolve(Request.post(`${api_version}/lottery/scan`, {
                        shift_id: shift.id,
                        store_id: store.id,
                        code: code,
                    }), 1000));
                })
        };
        queue.add(task);
        setItemId(n => n + 1);
    };

    const [changeScanTimer, setChangeScanTimer] = useState(0);
    const changeWait = (callBack) => {
        if (changeScanTimer)
            clearTimeout(changeScanTimer);
        setChangeScanTimer(setTimeout(callBack, 500));
    }

    const onScannedBarcode = (value) => {
        if (isNumeric(value) && value.length > 16) {
            callApi(value)
            changeWait(() => (scanCodeInput.current.value = ''))
            // Store.dispatch(setSnackbarMessage(SnackBarStatus.success, 'Successful!', 2000))
        } else {
            changeWait(() => (scanCodeInput.current.value = ''));
            // Store.dispatch(setSnackbarMessage(SnackBarStatus.error, 'Invalid. Please scan again!', 2000))
        }
    }

    const {numInFlight, numPending} = queue.stats;

    return <>
        <div/>
    </>
}
const mapStateToProps = (state) => ({
    shift: state.App.shift,
    store: state.App.store
})
export default connect(mapStateToProps)(LotteryScan)

And This is how I am using LotteryScan component in index.js

<div>
    {
        daily_scan[1] !== undefined &&
        (isArray(daily_scan[1]) || daily_scan[1][0] !== undefined) &&
        Object.keys(daily_scan)
            .map((key) =>
                <LotteryScan title={'Lottery Scanned (Shift: ' + key + ')'} Key={key}
                             key={key + shift.id} daily_scan={daily_scan[key]}/>)
    }
    {
        isArray(daily_scan) &&
        <LotteryScan Key={0} daily_scan={daily_scan} key={1 + shift.id}/>
    }
</div>

When I delete this then the error stops...

const queue = useAsyncQueue({
        concurrency: 1,
        inflight,
        drain,
        done
    });

I believe the problem is that I specified react as a dependency rather than a peer dependency. I published a new version 2.1.5 -- please give it a try and see if that fixes it!

Thank you! It is working ...