prepair redux
This commit is contained in:
9
redux/actions.js
Normal file
9
redux/actions.js
Normal file
@@ -0,0 +1,9 @@
|
||||
// /redux/actions.js
|
||||
export const connectWebSocket = (url) => ({
|
||||
type: "WS_CONNECT",
|
||||
payload: { url },
|
||||
});
|
||||
|
||||
export const disconnectWebSocket = () => ({
|
||||
type: "WS_DISCONNECT",
|
||||
});
|
||||
18
redux/reducer.js
Normal file
18
redux/reducer.js
Normal file
@@ -0,0 +1,18 @@
|
||||
// /redux/reducer.js
|
||||
const initialState = {
|
||||
messages: [],
|
||||
};
|
||||
|
||||
const websocketReducer = (state = initialState, action) => {
|
||||
switch (action.type) {
|
||||
case "WS_MESSAGE_RECEIVED":
|
||||
return {
|
||||
...state,
|
||||
messages: [...state.messages, action.payload],
|
||||
};
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
};
|
||||
|
||||
export default websocketReducer;
|
||||
8
redux/store.js
Normal file
8
redux/store.js
Normal file
@@ -0,0 +1,8 @@
|
||||
// /redux/store.js
|
||||
import { createStore, applyMiddleware } from "redux";
|
||||
import websocketMiddleware from "./websocketMiddleware";
|
||||
import websocketReducer from "./reducer";
|
||||
|
||||
const store = createStore(websocketReducer, applyMiddleware(websocketMiddleware));
|
||||
|
||||
export default store;
|
||||
29
redux/websocketMiddleware.js
Normal file
29
redux/websocketMiddleware.js
Normal file
@@ -0,0 +1,29 @@
|
||||
// /redux/websocketMiddleware.js
|
||||
const websocketMiddleware = () => {
|
||||
let socket;
|
||||
|
||||
return ({ dispatch }) =>
|
||||
(next) =>
|
||||
(action) => {
|
||||
if (action.type === "WS_CONNECT") {
|
||||
socket = new WebSocket(action.payload.url);
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
dispatch({ type: "WS_MESSAGE_RECEIVED", payload: data });
|
||||
};
|
||||
|
||||
socket.onclose = () => {
|
||||
dispatch({ type: "WS_DISCONNECTED" });
|
||||
};
|
||||
}
|
||||
|
||||
if (action.type === "WS_DISCONNECT" && socket) {
|
||||
socket.close();
|
||||
}
|
||||
|
||||
return next(action);
|
||||
};
|
||||
};
|
||||
|
||||
export default websocketMiddleware;
|
||||
Reference in New Issue
Block a user