0
votes

WebSocket setup -

const webSocketSetup = () => {
    const ws = useRef(null);

    const dispatch = useDispatch();

    useEffect(() => {
        const socket = new WebSocket(url);

        socket.onopen = () => {
            dispatch(wsSlice.setWSParams({ key: 'isReady', value: true }));
            dispatch(wsSlice.setWSParams({ key: 'send', value: socket.send.bind(socket) }));
        };
        socket.onclose = () => {
            dispatch(wsSlice.setWSParams({ key: 'isReady', value: false }));
        };

        ws.current = socket;
        ws.current.onmessage = (event) => {
            sliceInjector(JSON.parse(event?.data));
        };
    }, []);

    return null;
};

In the setup, every event is sent to sliceInjector function.

sliceInjector -

import { store } from '../redux/store';

const sliceInjector = (event) => {
    switch (event?.type) {
        case 'eventType_1':
            store.dispatch(eventType_1.setData(event));
            break;
        case 'eventType_2':
            store.dispatch(eventType_2.setData(event));
            break;
        case 'eventType_3':
            store.dispatch(eventType_3.setData(event));
            break;
        default:
            return false;
    }
};

In the sliceInjector, each event is sent to a diffrent slice base on the event.type.

eventType_1 slice -

const eventType_1 = createSlice({
    name: 'eventType_1',
    initialState: {
        data: {},
    },

    reducers: {
        setData: (state, action) => {
            const obj = { ...state.data, [action.payload.id]: action.payload };
            state.data = obj;
        },
    },
});

export const { setData, updateData, deleteData } = eventType_1.actions;

export default eventType_1.reducer;

Component which sending & getting data from eventType_1 -

 const component = (props) => {
    const ready = useSelector((state) => state.wsState.wsParams.isReady);
    const send = useSelector((state) => state.wsState.wsParams.send);
    const eventType_1 = useSelector((state) => state.eventType_1.data);

    useEffect(() => {
    if (ready) {
        send(
        JSON.stringify({
            id: id,
            type: "eventType_1 ",
            data: {
            products: ["product_1", "product_2"],
            },
        })
        );
    }
    }, [ready]);

    console.log(eventType_1)
}

In the component file I send event to server with send from useSelector. And get the data with eventType_1 from useSelector.

The issue is that when I send multiple events from diffrent components, the "flow" of the events gets broken, the ws on network tab waits for some of the events and I can't figure out why.

What I want to understand is what's wrong with the flow. How can I build a flow with ws & react & redux/toolkit, for complex ws multiple event sending in concurrent way that will update all the components in parallel.