Issues with Initial State Allocation in React Context for Counter Simulation

I’m working on a React project where I’m simulating a bank counter system. The system has the following components:

1: Context Provider (BankCounterContext.js): Manages the state of the counters and the queue.
2: Counter Component (Counter.js): Represents individual counters that process items from the queue.
3: Initial Settings Component (InitialSettings.js): Allows setting initial processing times for counters and the initial queue length.

When I click on the “Change” button to set the initial state, the first four items from the queue should be assigned to the counters for processing. These items should appear in the “Processing” column before moving to the “Processed” column based on their processing time. However, the items are directly appearing in the “Processed” column without showing in the “Processing” column.

BankCounterContext.js:

"use client";
import { createContext, useContext, useState, useEffect, useCallback } from "react";
export const BankCounterContext = createContext({});
export const BankCounterContextProvider = ({ children }) => {
  const [initialCounters, setInitialCounters] = useState([
    { id: 1, processingTime: 0, status: "idle", current: null, processed: [] },
    { id: 2, processingTime: 0, status: "idle", current: null, processed: [] },
    { id: 3, processingTime: 0, status: "idle", current: null, processed: [] },
    { id: 4, processingTime: 0, status: "idle", current: null, processed: [] },
  ]);
  const [initialQueue, setInitialQueue] = useState([]);
  const [processStatus, setProcessStatus] = useState(false);
  const setInitialCountersFunc = (newCounters) => {
    setInitialCounters(newCounters);
    setInitialQueue([]);
  };
  const updateCounterStatus = (id, status, current = null) => {
    setInitialCounters(prevCounters =>
      prevCounters.map(counter =>
        counter.id === id ? { ...counter, status, current } : counter
      )
    );
  };
  const getNextItemFromQueue = useCallback(() => {
    if (initialQueue.length > 0) {
      const nextItem = initialQueue.shift();
      setInitialQueue([...initialQueue]);
      return nextItem;
    }
    return null;
  }, [initialQueue]);
  const allocateNextClientToCounter = useCallback((counter) => {
    const nextItem = getNextItemFromQueue();
    if (nextItem !== null) {
      updateCounterStatus(counter.id, "processing", nextItem);
      setTimeout(() => {
        setInitialCounters(prevCounters =>
          prevCounters.map(c =>
            c.id === counter.id ? {
              ...c,
              status: "idle",
              processed: [...c.processed, nextItem],
              current: null
            } : c
          )
        );
      }, counter.processingTime * 1000);
    }
  }, [getNextItemFromQueue]);
  useEffect(() => {
    if (processStatus) {
      initialCounters
        .filter(counter => counter.status === "idle")
        .forEach(counter => allocateNextClientToCounter(counter));
    }
  }, [initialCounters, processStatus, allocateNextClientToCounter]);
  return (
    <BankCounterContext.Provider
      value={{
        initialCounters,
        setInitialCounters,
        initialQueue,
        setInitialQueue,
        setInitialCountersFunc,
        processStatus,
        setProcessStatus,
        updateCounterStatus,
        getNextItemFromQueue,
        allocateNextClientToCounter,
      }}
    >
      {children}
    </BankCounterContext.Provider>
  );
};
export const useMultiContext = () => useContext(BankCounterContext);

InitialSettings.js Component

"use client";

import { useState, useContext } from "react";
import { BankCounterContext } from "@/context/bank_counter_context";

const InitialSettings = () => {
  const { setInitialCounters, setInitialQueue, setProcessStatus, allocateNextClientToCounter } =
    useContext(BankCounterContext);
  const [settings, setSettings] = useState({
    counter1: 0,
    counter2: 0,
    counter3: 0,
    counter4: 0,
    startNumber: 0,
  });

  const handleChange = (e) => {
    const { name, value } = e.target;
    setSettings((prev) => ({
      ...prev,
      [name]: value !== "" ? parseInt(value) : "",
    }));
  };

  const applySettings = () => {
    const newCounters = [
      { id: 1, processingTime: settings.counter1 || 0, status: "idle", current: null, processed: [] },
      { id: 2, processingTime: settings.counter2 || 0, status: "idle", current: null, processed: [] },
      { id: 3, processingTime: settings.counter3 || 0, status: "idle", current: null, processed: [] },
      { id: 4, processingTime: settings.counter4 || 0, status: "idle", current: null, processed: [] },
    ];
    setInitialCounters(newCounters);

    const queue = Array.from({ length: settings.startNumber || 0 }, (_, i) => i + 1);
    setInitialQueue(queue);

    setProcessStatus(true);

    newCounters.forEach(counter => allocateNextClientToCounter(counter));
  };

  return (
    <div className="flex flex-col gap-4">
      <div>
        <label className="flex justify-center gap-4">
          Counter 1 Processing Time:
          <input
            type="number"
            name="counter1"
            value={settings.counter1}
            onChange={handleChange}
            className="text-black border pl-2 border-gray-600"
          />
        </label>
      </div>
      <div>
        <label className="flex justify-center gap-4">
          Counter 2 Processing Time:
          <input
            type="number"
            name="counter2"
            value={settings.counter2}
            onChange={handleChange}
            className="text-black border pl-2 border-gray-600"
          />
        </label>
      </div>
      <div>
        <label className="flex justify-center gap-4">
          Counter 3 Processing Time:
          <input
            type="number"
            name="counter3"
            value={settings.counter3}
            onChange={handleChange}
            className="text-black border pl-2 border-gray-600"
          />
        </label>
      </div>
      <div>
        <label className="flex justify-center gap-4">
          Counter 4 Processing Time:
          <input
            type="number"
            name="counter4"
            value={settings.counter4}
            onChange={handleChange}
            className="text-black border pl-2 border-gray-600"
          />
        </label>
      </div>
      <div>
        <label className="flex justify-center gap-4">
          Start Number:
          <input
            type="number"
            name="startNumber"
            value={settings.startNumber}
            onChange={handleChange}
            className="text-black border pl-2 border-gray-600"
          />
        </label>
      </div>
      <button
        onClick={applySettings}
        className="inline-block w-40 mx-auto my-6 rounded-lg font-medium text-white bg-[#67e9ff] hover:bg-[#62d7eb] dark:bg-teal-700 hover:dark:bg-teal-500 py-2 px-5 transition duration-150 ease-in-out"
      >
        Change
      </button>
    </div>
  );
};

export default InitialSettings;

Queue.js Component

"use client"

import { useState, useEffect, useCallback, useContext } from "react";
import Counter from "./Counter";
import { BankCounterContext } from "@/context/bank_counter_context";

const Queue = () => {
  const {initialCounters, initialQueue, processStatus} = useContext(BankCounterContext);
  const [queue, setQueue] = useState([]);
  const [counters, setCounters] = useState(initialCounters);

  useEffect(() => {
    if (processStatus) {

      setQueue(initialQueue);
    }
  }, [initialQueue, processStatus]);

  useEffect(() => {
    setCounters(initialCounters);
  }, [initialCounters]);

  const addPersonToQueue = () => {
    setQueue([...queue, queue.length + 1]);
  };

  const onCounterIdle = (counterId) => {
    setCounters((prev) =>
      prev.map((counter) =>
        counter.id === counterId ? { ...counter, status: "idle" } : counter
      )
    );
  };

  const allocateClients = useCallback(() => {
    const idleCounters = counters.filter(
      (counter) => counter.status === "idle"
    );
    if (idleCounters.length > 0 && queue.length > 0) {
      const nextClient = queue[0];
      const remainingQueue = queue.slice(1);
      const nextCounter = idleCounters.sort((a, b) => a.id - b.id)[0];
      setQueue(remainingQueue);
      setCounters((prev) =>
        prev.map((counter) =>
          counter.id === nextCounter.id
            ? { ...counter, status: "processing", current: nextClient }
            : counter
        )
      );
    }
  }, [queue, counters]);

  useEffect(() => {
    const interval = setInterval(() => {
      allocateClients();
    }, 0);
    return () => clearInterval(interval);
  }, [allocateClients]);

  return (
    <div className="text-center border-b pb-8 mb-8">
      <table className="min-w-full border text-center text-sm font-light border-gray-400 dark:border-neutral-500">
        <thead className="border-b font-medium border-gray-400 dark:border-neutral-500">
          <tr>
            <th className="border-r px-6 py-4 border-gray-400 dark:border-neutral-500">
              Counter
            </th>
            <th className="border-r px-6 py-4 border-gray-400 dark:border-neutral-500">
              Processing
            </th>
            <th className="border-r px-6 py-4 border-gray-400 dark:border-neutral-500">
              Processed
            </th>
          </tr>
        </thead>
        <tbody>
          {counters.map((counter) => {
            return (
              <Counter
              key={counter.id}
              id={counter.id}
              processingTime={counter.processingTime}
              status={counter.status}
              onIdle={onCounterIdle}
            />
            )
          })}
        </tbody>
      </table>
      <div className="my-6">Number of people waiting: {queue.length}</div>
      <button
        onClick={addPersonToQueue}
        className="inline-block w-40 mx-auto my-6 rounded-lg font-medium text-white bg-[#67e9ff] hover:bg-[#62d7eb] dark:bg-teal-700 hover:dark:bg-teal-500 py-2 px-5 transition duration-150 ease-in-out"
      >
        Next {queue.length + 1}
      </button>
    </div>
  );
};

export default Queue;

Counter.js Component

"use client";

import { useEffect, useContext } from "react";
import { BankCounterContext } from "@/context/bank_counter_context";

const Counter = ({ id }) => {
  const {
    initialCounters,
    processStatus,
    allocateNextClientToCounter
  } = useContext(BankCounterContext);
  const counter = initialCounters.find(counter => counter.id === id);
  const { status, current, processed } = counter;

  useEffect(() => {
    if (processStatus && status === 'idle') {
      allocateNextClientToCounter(counter);
    }
  }, [processStatus, status, counter, allocateNextClientToCounter]);

  return (
    <tr className="text-center border-b border-gray-400 dark:border-neutral-500">
      <td className="whitespace-nowrap text-black dark:text-white border-r px-6 py-4 font-medium border-gray-400 dark:border-neutral-500">{`Counter ${id}`}</td>
      <td className="whitespace-nowrap text-black dark:text-white border-r px-6 py-4 font-medium border-gray-400 dark:border-neutral-500">
        {status === "idle" ? "idle" : `${current}`}
      </td>
      <td className="whitespace-nowrap text-black dark:text-white border-r px-6 py-4 font-medium border-gray-400 dark:border-neutral-500">
        {processed.join(", ")}
      </td>
    </tr>
  );
};

export default Counter;
[enter image description here](https://i.sstatic.net/l8C5YB9F.png)

The items from the queue should first appear in the “Processing” column before moving to the “Processed” column

I have tried many ways to solve it but they didn’t work, any help will be appreciated

New contributor

John Doe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật