├── .gitignore
├── README.md
├── package-lock.json
├── package.json
├── public
├── favicon.ico
├── index.html
├── logo192.png
├── logo512.png
├── manifest.json
└── robots.txt
└── src
├── App.css
├── App.js
├── App.test.js
├── components
├── FirstPerson.js
├── PersonSwitcher.js
├── SecondPerson.js
└── index.js
├── index.css
├── index.js
├── logo.svg
├── serviceWorker.js
└── store
└── chat.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
2 |
3 | # dependencies
4 | /node_modules
5 | /.pnp
6 | .pnp.js
7 |
8 | # testing
9 | /coverage
10 |
11 | # production
12 | /build
13 |
14 | # misc
15 | .DS_Store
16 | .env.local
17 | .env.development.local
18 | .env.test.local
19 | .env.production.local
20 |
21 | npm-debug.log*
22 | yarn-debug.log*
23 | yarn-error.log*
24 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | This app was built from my article on [RxJS with React Hooks for state management](https://blog.logrocket.com/rxjs-with-react-hooks-for-state-management)
2 |
3 | Link to hosted app: [rxjs-react-chat](https://rxjs-react-chat.netlify.com)
4 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "rxjs_react_chat",
3 | "version": "0.1.0",
4 | "private": true,
5 | "dependencies": {
6 | "react": "^16.11.0",
7 | "react-dom": "^16.11.0",
8 | "react-router-dom": "^5.1.2",
9 | "react-scripts": "3.2.0"
10 | },
11 | "scripts": {
12 | "start": "react-scripts start",
13 | "build": "react-scripts build",
14 | "test": "react-scripts test",
15 | "eject": "react-scripts eject"
16 | },
17 | "eslintConfig": {
18 | "extends": "react-app"
19 | },
20 | "browserslist": {
21 | "production": [
22 | ">0.2%",
23 | "not dead",
24 | "not op_mini all"
25 | ],
26 | "development": [
27 | "last 1 chrome version",
28 | "last 1 firefox version",
29 | "last 1 safari version"
30 | ]
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/public/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ebenezerdon/rxjs_react_chat/04df85528ad3cbb80b2cd492c81ac8249f85859d/public/favicon.ico
--------------------------------------------------------------------------------
/public/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
12 |
13 |
17 |
18 |
27 | React App
28 |
29 |
30 |
31 |
32 |
42 |
43 |
44 |
--------------------------------------------------------------------------------
/public/logo192.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ebenezerdon/rxjs_react_chat/04df85528ad3cbb80b2cd492c81ac8249f85859d/public/logo192.png
--------------------------------------------------------------------------------
/public/logo512.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/ebenezerdon/rxjs_react_chat/04df85528ad3cbb80b2cd492c81ac8249f85859d/public/logo512.png
--------------------------------------------------------------------------------
/public/manifest.json:
--------------------------------------------------------------------------------
1 | {
2 | "short_name": "React App",
3 | "name": "Create React App Sample",
4 | "icons": [
5 | {
6 | "src": "favicon.ico",
7 | "sizes": "64x64 32x32 24x24 16x16",
8 | "type": "image/x-icon"
9 | },
10 | {
11 | "src": "logo192.png",
12 | "type": "image/png",
13 | "sizes": "192x192"
14 | },
15 | {
16 | "src": "logo512.png",
17 | "type": "image/png",
18 | "sizes": "512x512"
19 | }
20 | ],
21 | "start_url": ".",
22 | "display": "standalone",
23 | "theme_color": "#000000",
24 | "background_color": "#ffffff"
25 | }
26 |
--------------------------------------------------------------------------------
/public/robots.txt:
--------------------------------------------------------------------------------
1 | # https://www.robotstxt.org/robotstxt.html
2 | User-agent: *
3 |
--------------------------------------------------------------------------------
/src/App.css:
--------------------------------------------------------------------------------
1 | .container {
2 | font-family: Arial, Helvetica, sans-serif;
3 | padding: 1em;
4 | }
5 |
6 | .chat-box {
7 | background: #202020;
8 | margin: auto;
9 | padding: 2em;
10 | height: 35em;
11 | width: 95%;
12 | border-radius: 20px;
13 | overflow-y: scroll;
14 | }
15 |
16 | .first-person, .second-person {
17 | display: inline-block;
18 | color: #fff;
19 | height: 25px;
20 | min-width: 20%;
21 | max-width: 60%;
22 | padding: 20px;
23 | text-align: center;
24 | vertical-align: middle;
25 | border-radius: 30px;
26 | }
27 |
28 | .first-person {
29 | background: rgb(0, 173, 231);
30 | }
31 |
32 | .second-person {
33 | background: #06c406;
34 | float: right;
35 | }
36 |
37 | .clear{
38 | clear: both;
39 | display: block;
40 | content: "";
41 | width: 100%;
42 | }
43 |
44 | .switcher-div {
45 | padding-top: 1em;
46 | text-align: center;
47 | }
48 |
49 | #messageForm {
50 | text-align: center;
51 | margin-top: 1.5em;
52 | }
53 |
54 | #messageForm input {
55 | height: 2em;
56 | width: 23em;
57 | border-radius: 3em;
58 | padding: 1em;
59 | }
60 |
61 | #messageForm button {
62 | margin-left: 2em;
63 | height: 2.7em;
64 | width: 6.2em;
65 | border-radius: 25px;
66 | border: none;
67 | cursor: pointer;
68 | }
69 |
70 | .clear-button {
71 | background: #d40000;
72 | color: #fff;
73 | float: right;
74 | margin-right: 3em;
75 | text-align: center;
76 | height: 2.5em;
77 | width: 8em;
78 | cursor: pointer;
79 | }
80 |
81 | .switcher {
82 | background: #cecece;
83 | color: #141414;
84 | height: 2.5em;
85 | width: 6em;
86 | border-radius: 25px;
87 | border: 1 px solid black;
88 | margin-right: 1em;
89 | cursor: pointer;
90 | }
91 |
92 | .notify {
93 | position: absolute;
94 | background: #db0000;
95 | color: white;
96 | height: 1em;
97 | width: 1em;
98 | border-radius: 100%;
99 | padding: 0.15em;
100 | margin-left: 0.5em;
101 | margin-top: -0.5em;
102 | }
103 |
--------------------------------------------------------------------------------
/src/App.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
3 | import { FirstPerson, SecondPerson, PersonSwitcher } from './components';
4 | import './App.css';
5 |
6 | const App = () => (
7 |
8 | <>
9 |
10 |
11 | >
12 | >
13 | >
14 |
15 | >
16 |
17 | );
18 |
19 | export default App;
20 |
--------------------------------------------------------------------------------
/src/App.test.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import App from './App';
4 |
5 | it('renders without crashing', () => {
6 | const div = document.createElement('div');
7 | ReactDOM.render(, div);
8 | ReactDOM.unmountComponentAtNode(div);
9 | });
10 |
--------------------------------------------------------------------------------
/src/components/FirstPerson.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useLayoutEffect } from "react";
2 | import chatStore from '../store/chat';
3 |
4 | const FirstPerson = () => {
5 | const [chatState, setChatState] = useState(chatStore.initialState);
6 |
7 | useLayoutEffect(()=> {
8 | const subs = chatStore.subscribe(setChatState);
9 | chatStore.init();
10 |
11 | return () => subs.unsubscribe();
12 | },[]);
13 |
14 | const onFormSubmit = e => {
15 | e.preventDefault();
16 | const messageObject = {
17 | person: 'first-person',
18 | text: e.target.elements.messageInput.value.trim(),
19 | };
20 | chatStore.sendMessage(messageObject);
21 | document.getElementById('messageForm').reset();
22 | };
23 |
24 | return (
25 |
26 |
Mycroft
27 |
28 | {chatState.data.map(message => (
29 |
30 |
{message.text}
31 |
32 |
33 | ))}
34 |
35 |
45 |
48 |
49 | );
50 | }
51 |
52 | export default FirstPerson;
--------------------------------------------------------------------------------
/src/components/PersonSwitcher.js:
--------------------------------------------------------------------------------
1 | import React, {useState, useEffect} from 'react';
2 | import { Link } from 'react-router-dom';
3 | import chatStore from '../store/chat';
4 |
5 | const PersonSwitcher = () => {
6 | const [chatState, setChatState] = useState(chatStore.initialState);
7 | const location = window.location.href.split('/')[3];
8 |
9 | useEffect(() => {
10 | chatStore.subscribe(setChatState);
11 | chatStore.init();
12 | }, [])
13 |
14 | const messageNotification = chatState.newDataCount > 0
15 | && ({chatState.newDataCount});
16 |
17 | return (
18 |
19 |
23 |
27 |
28 | );
29 | }
30 |
31 | export default PersonSwitcher;
32 |
--------------------------------------------------------------------------------
/src/components/SecondPerson.js:
--------------------------------------------------------------------------------
1 | import React, { useState, useLayoutEffect } from "react";
2 | import chatStore from '../store/chat';
3 |
4 | const SecondPerson = () => {
5 | const [chatState, setChatState] = useState(chatStore.initialState);
6 |
7 | useLayoutEffect(()=> {
8 | const subs = chatStore.subscribe(setChatState);
9 | chatStore.init();
10 |
11 | return () => subs.unsubscribe();
12 | },[]);
13 |
14 | const onFormSubmit = e => {
15 | e.preventDefault();
16 | const messageObject = {
17 | person: 'second-person',
18 | text: e.target.elements.messageInput.value.trim(),
19 | };
20 | chatStore.sendMessage(messageObject);
21 | document.getElementById('messageForm').reset();
22 | };
23 |
24 | return (
25 |
26 |
Cortana
27 |
28 | {chatState.data.map(message => (
29 |
30 |
{message.text}
31 |
32 |
33 | ))}
34 |
35 |
44 |
47 |
48 | );
49 | }
50 |
51 | export default SecondPerson;
52 |
--------------------------------------------------------------------------------
/src/components/index.js:
--------------------------------------------------------------------------------
1 | export { default as FirstPerson } from './FirstPerson';
2 | export { default as SecondPerson } from './SecondPerson';
3 | export { default as PersonSwitcher } from './PersonSwitcher';
4 |
--------------------------------------------------------------------------------
/src/index.css:
--------------------------------------------------------------------------------
1 | body {
2 | margin: 0;
3 | font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen",
4 | "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue",
5 | sans-serif;
6 | -webkit-font-smoothing: antialiased;
7 | -moz-osx-font-smoothing: grayscale;
8 | }
9 |
10 | code {
11 | font-family: source-code-pro, Menlo, Monaco, Consolas, "Courier New",
12 | monospace;
13 | }
14 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import React from 'react';
2 | import ReactDOM from 'react-dom';
3 | import './index.css';
4 | import App from './App';
5 | import * as serviceWorker from './serviceWorker';
6 |
7 | ReactDOM.render(, document.getElementById('root'));
8 |
9 | // If you want your app to work offline and load faster, you can change
10 | // unregister() to register() below. Note this comes with some pitfalls.
11 | // Learn more about service workers: https://bit.ly/CRA-PWA
12 | serviceWorker.unregister();
13 |
--------------------------------------------------------------------------------
/src/logo.svg:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/src/serviceWorker.js:
--------------------------------------------------------------------------------
1 | // This optional code is used to register a service worker.
2 | // register() is not called by default.
3 |
4 | // This lets the app load faster on subsequent visits in production, and gives
5 | // it offline capabilities. However, it also means that developers (and users)
6 | // will only see deployed updates on subsequent visits to a page, after all the
7 | // existing tabs open on the page have been closed, since previously cached
8 | // resources are updated in the background.
9 |
10 | // To learn more about the benefits of this model and instructions on how to
11 | // opt-in, read https://bit.ly/CRA-PWA
12 |
13 | const isLocalhost = Boolean(
14 | window.location.hostname === 'localhost' ||
15 | // [::1] is the IPv6 localhost address.
16 | window.location.hostname === '[::1]' ||
17 | // 127.0.0.1/8 is considered localhost for IPv4.
18 | window.location.hostname.match(
19 | /^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
20 | )
21 | );
22 |
23 | export function register(config) {
24 | if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
25 | // The URL constructor is available in all browsers that support SW.
26 | const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
27 | if (publicUrl.origin !== window.location.origin) {
28 | // Our service worker won't work if PUBLIC_URL is on a different origin
29 | // from what our page is served on. This might happen if a CDN is used to
30 | // serve assets; see https://github.com/facebook/create-react-app/issues/2374
31 | return;
32 | }
33 |
34 | window.addEventListener('load', () => {
35 | const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
36 |
37 | if (isLocalhost) {
38 | // This is running on localhost. Let's check if a service worker still exists or not.
39 | checkValidServiceWorker(swUrl, config);
40 |
41 | // Add some additional logging to localhost, pointing developers to the
42 | // service worker/PWA documentation.
43 | navigator.serviceWorker.ready.then(() => {
44 | console.log(
45 | 'This web app is being served cache-first by a service ' +
46 | 'worker. To learn more, visit https://bit.ly/CRA-PWA'
47 | );
48 | });
49 | } else {
50 | // Is not localhost. Just register service worker
51 | registerValidSW(swUrl, config);
52 | }
53 | });
54 | }
55 | }
56 |
57 | function registerValidSW(swUrl, config) {
58 | navigator.serviceWorker
59 | .register(swUrl)
60 | .then(registration => {
61 | registration.onupdatefound = () => {
62 | const installingWorker = registration.installing;
63 | if (installingWorker == null) {
64 | return;
65 | }
66 | installingWorker.onstatechange = () => {
67 | if (installingWorker.state === 'installed') {
68 | if (navigator.serviceWorker.controller) {
69 | // At this point, the updated precached content has been fetched,
70 | // but the previous service worker will still serve the older
71 | // content until all client tabs are closed.
72 | console.log(
73 | 'New content is available and will be used when all ' +
74 | 'tabs for this page are closed. See https://bit.ly/CRA-PWA.'
75 | );
76 |
77 | // Execute callback
78 | if (config && config.onUpdate) {
79 | config.onUpdate(registration);
80 | }
81 | } else {
82 | // At this point, everything has been precached.
83 | // It's the perfect time to display a
84 | // "Content is cached for offline use." message.
85 | console.log('Content is cached for offline use.');
86 |
87 | // Execute callback
88 | if (config && config.onSuccess) {
89 | config.onSuccess(registration);
90 | }
91 | }
92 | }
93 | };
94 | };
95 | })
96 | .catch(error => {
97 | console.error('Error during service worker registration:', error);
98 | });
99 | }
100 |
101 | function checkValidServiceWorker(swUrl, config) {
102 | // Check if the service worker can be found. If it can't reload the page.
103 | fetch(swUrl)
104 | .then(response => {
105 | // Ensure service worker exists, and that we really are getting a JS file.
106 | const contentType = response.headers.get('content-type');
107 | if (
108 | response.status === 404 ||
109 | (contentType != null && contentType.indexOf('javascript') === -1)
110 | ) {
111 | // No service worker found. Probably a different app. Reload the page.
112 | navigator.serviceWorker.ready.then(registration => {
113 | registration.unregister().then(() => {
114 | window.location.reload();
115 | });
116 | });
117 | } else {
118 | // Service worker found. Proceed as normal.
119 | registerValidSW(swUrl, config);
120 | }
121 | })
122 | .catch(() => {
123 | console.log(
124 | 'No internet connection found. App is running in offline mode.'
125 | );
126 | });
127 | }
128 |
129 | export function unregister() {
130 | if ('serviceWorker' in navigator) {
131 | navigator.serviceWorker.ready.then(registration => {
132 | registration.unregister();
133 | });
134 | }
135 | }
136 |
--------------------------------------------------------------------------------
/src/store/chat.js:
--------------------------------------------------------------------------------
1 | import { Subject } from 'rxjs';
2 |
3 | const subject = new Subject();
4 | const initialState = {
5 | status: '',
6 | data: [],
7 | newDataCount: 0,
8 | error: ''
9 | };
10 |
11 | let state = initialState;
12 |
13 | const chatStore = {
14 | init: () => {
15 | state = {...state, newDataCount: 0}
16 | subject.next(state)
17 | },
18 | subscribe: setState => subject.subscribe(setState),
19 | sendMessage: message => {
20 | state = {
21 | ...state,
22 | data: [...state.data, message],
23 | newDataCount: state.newDataCount + 1
24 | };
25 | subject.next(state);
26 | },
27 | clearChat: () => {
28 | state = initialState;
29 | subject.next(state);
30 | },
31 | initialState
32 | };
33 |
34 | export default chatStore;
35 |
--------------------------------------------------------------------------------