retropilot-client/src/context/devices/index.js

69 lines
1.4 KiB
JavaScript
Raw Normal View History

2022-01-09 18:40:47 -07:00
import React, {
createContext,
useEffect,
useMemo,
useReducer,
} from 'react';
import PropTypes from 'prop-types';
2022-01-09 09:52:29 -07:00
2022-01-09 18:40:47 -07:00
import * as deviceController from '../../controllers/devices';
2022-01-09 09:52:29 -07:00
2022-01-09 18:40:47 -07:00
import ACTIONS from './actions';
import reducer from './reducer';
2022-01-05 09:55:56 -07:00
const initialState = {
2022-01-09 09:52:29 -07:00
dongles: {},
2022-01-05 09:55:56 -07:00
};
2022-01-03 09:30:54 -07:00
2022-01-09 18:40:47 -07:00
const DevicesContext = createContext(initialState);
function DevicesProvider({ children }) {
const [state, dispatch] = useReducer(reducer, initialState);
2022-01-09 09:52:29 -07:00
useEffect(() => {
const ws = new WebSocket('ws://localhost:81');
ws.onmessage = ({ data }) => {
2022-01-09 18:40:47 -07:00
const payload = JSON.parse(data);
console.log('devices onmessage', payload);
if (!payload.id) {
dispatch({ type: ACTIONS.ADD_DATA, data: payload });
2022-01-09 09:52:29 -07:00
}
};
deviceController.getAllDevices().then((devices) => {
2022-01-09 18:40:47 -07:00
console.log('devices store', devices);
2022-01-09 09:52:29 -07:00
2022-01-09 18:40:47 -07:00
dispatch({ type: ACTIONS.FETCH_ALL_DONGLES, data: devices });
2022-01-09 09:52:29 -07:00
});
return () => {
2022-01-09 18:40:47 -07:00
// Clean up the websocket
2022-01-09 09:52:29 -07:00
try {
ws.close();
2022-01-09 18:40:47 -07:00
} catch (e) {
// do nothing
}
2022-01-09 09:52:29 -07:00
};
}, []);
2022-01-09 18:40:47 -07:00
const contextValue = useMemo(() => ([state, dispatch]), [state, dispatch]);
2022-01-09 09:52:29 -07:00
return (
2022-01-09 18:40:47 -07:00
<DevicesContext.Provider value={contextValue}>
{ children }
</DevicesContext.Provider>
2022-01-09 09:52:29 -07:00
);
}
2022-01-03 09:30:54 -07:00
2022-01-09 18:40:47 -07:00
DevicesProvider.propTypes = {
children: PropTypes.node.isRequired,
};
export default DevicesProvider;
export {
ACTIONS,
DevicesContext,
};