Search code examples
reactjsreduxreact-hooksmiddleware

Converting Redux to React Context API + useReducer


I am in the process of converting my redux structure to Context API combined with useReducer. Everything is working as intended, however I had a web socket middleware, which I bound to redux with applyMiddleware and redux-thunk. Really confused on how can I bind the middleware to work with my structure.

MyContext.js

import { createContext } from 'react'

export const initialState = {
    values : {}
}

export const Context = createContext(initialState)

MyProvider.js

import { monitoring } from './reducers/monitoring'
import { Context, initialState } from './monitoringContext'
import { useReducerWithMiddleware } from './reducerMiddleware'

export const MonitoringProvider = ({ middleware, children }) => {
    const [state, dispatch] = useReducerWithMiddleware(monitoring, initialState, middleware)

    return (
        <Context.Provider value={{ state, dispatch }}>
            {children}
        </Context.Provider>
    )
}

useReducerMiddleware.js (implemented redux-thunk alike structure here)

import { useReducer } from "react";

export const useReducerWithMiddleware = (reducer, initialState, middleware) => {
    const [state, dispatch] = useReducer(reducer, initialState);
    const thunkDispatch = action => {
    if (typeof action === "function") {
      return action(thunkDispatch, state)
    }

    return middleware(dispatch(action))
  };
    return [state, thunkDispatch];
};

I bind the provider like this:

  <MonitoringProvider middleware={reducerSocketMiddleware}> // This is the socketFunction provided below
      <Layout /> // This is a component that handles all the routing
   </MonitoringProvider>

And I want to bind the socketFunction middleware. Right now, none of the actions dispatched are going through this middleware.

socketFunction:

const socketFunction = store => next => action => {
    debugger // No visits to this debugger
    if (action.type === SOCKET_ACTION_TYPES.CONNECT_SOCKET_IO) {
        /* Connect socket */
    } else if (action.type === SOCKET_ACTION_TYPES.DISCONNECT_SOCKET_IO) {
        if (socket) socket.close(CLOSE_SIG)
    } else {
        return next(action)
    }
}


Solution

  • I was not calling the middleware appropriately.

    middleware(state)(dispatch)(action)
    

    solved the problem.