coordinating shared state

This commit is contained in:
2022-06-04 13:44:49 -05:00
parent 44a2db47bc
commit 603e75aafc
5 changed files with 63 additions and 14 deletions

View File

@@ -1,31 +1,51 @@
import { useState, useEffect } from 'react'
import logo from './logo.svg'
import io from 'socket.io-client'
// import './App.css'
import PlayerCard from './components/PlayerCard';
import "./styles.css";
function App() {
const [socket, setSocket] = useState();
const [state, setState] = useState({
socket: null,
players: null,
id: null,
})
useEffect(() => {
const newSocket = io("http://localhost:8000");
setSocket(newSocket);
setState({...state, socket: newSocket});
return () => newSocket.close();
}, [setSocket]);
}, []);
useEffect(() => {
if (!socket) return;
socket.on('connection', (data) => {
console.log('connected!' + data);
})
}, [socket]);
if (state.socket) {
state.socket.on('connect', (data) => {
console.log("connection to Express successful!");
console.log(data);
setState({
...state,
id: state.socket.id,
players: data
});
// state.socket.emit('connect', null);
})
}
}, [state.socket]);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>Hello Vite + React!</p>
</header>
<h1>Hello Vite + React!</h1>
{<h2>Your socket ID is: {state.id || ''}</h2>}
{<h3>Active players: {state.players || ''}</h3>}
<div className="players">
<PlayerCard name="Me" votes={null} />
</div>
</div>
)
}

View File

View File

@@ -0,0 +1,7 @@
export default function PlayerCard({ name, votes }) {
return (
<>
<h1>Name: {name}</h1>
</>
)
}

7
client/src/styles.css Normal file
View File

@@ -0,0 +1,7 @@
.App {
display: flex;
flex-direction: column;
align-items: center;
background-color: lightgray;
height: max(900px, 100vh);
}