Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Redux-toolkit + Signalr

What is the best way to update the state with signalr? At this moment I dispatching data inside on method callback and accessing it using useSelector inside other component.
I wonder if this is the optimal approach.

useEffect(()=> {

 const connection = $.hubConnection("http://x.x.x.x/signalr", { useDefaultPath: false })
 const proxy = connection.createHubProxy("exampleHub")

 proxy.on("action", function(data) {
   dispatch(setStatus(data))
 }
})

Slice.js:

export const monitorSlice = createSlice({
  name: "example",
  initialState: { 
    status: {},
},
  reducers: {
    setStatus(state, {payload}) => {
      state.status = payload
    }
  }
});

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your approach will work,
Here is other approach that you can have:

Using your own middleware

Another approach that is more agnostic is to use a middleware

import { Middleware } from 'redux'
import { monitorActions } from './monitorSlice';
 
const monitorMiddleware: Middleware = store => next => action => {
  if (!monitorActions.startConnecting.match(action)) {
    return next(action);
  }

  const connection = $.hubConnection("http://x.x.x.x/signalr", { useDefaultPath: false })
  const proxy = connection.createHubProxy("exampleHub")

  proxy.on("action", function(data) {
    dispatch(setStatus(data))
  });
 
  next(action);
}
 
export default monitorMiddleware;

Then inside your react app when you want to establish the connection

useEffect(()=> {
   dispatch(monitorActions.startConnecting())
}, [])

Then when you setup your store, do not forget to add your new middleware monitorMiddleware:

export const store = configureStore({
  reducer: rootReducer,
  middleware: (getDefaultMiddleware) => {
    return getDefaultMiddleware().concat([monitorMiddleware])
  },
});

Using create api

Another approach is to use createApi.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading