Telirw
Telirw

Reputation: 443

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
    }
  }
});

Upvotes: 1

Views: 2090

Answers (1)

Julien Kode
Julien Kode

Reputation: 5469

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.

Upvotes: 2

Related Questions