1
0
mirror of https://github.com/danbee/chess synced 2025-03-04 08:39:06 +00:00

Move all API/socket stuff to the App component

This commit is contained in:
Daniel Barber 2018-03-09 18:56:36 -05:00
parent 817514782e
commit f83e145379
Signed by: danbarber
GPG Key ID: 931D8112E0103DD8
3 changed files with 33 additions and 26 deletions

View File

@ -12,14 +12,41 @@ import chessBoardReducer from "./reducers/chess-board";
const store = createStore(chessBoardReducer);
import { setPlayer, setGame, setGameId } from "./store/actions";
import API from "./services/api";
import Channel from "./services/channel";
import ChessBoard from "./components/chess-board";
class App extends React.Component {
componentWillMount() {
const { gameId, store } = this.props;
store.dispatch(setGameId(gameId));
API.getGame(gameId)
.then(response => {
store.dispatch(setPlayer(response.data.player));
store.dispatch(setGame(response.data));
});
this.channel = Channel.gameChannel(gameId);
this.channel.on("game_update", data => {
store.dispatch(setGame(data));
});
}
sendMove(gameId, move) {
API.updateGame(gameId, move);
}
render() {
const { store, gameId } = this.props;
return (
<ChessBoard gameId={gameId} store={store} />
<ChessBoard gameId={gameId} store={store} sendMove={this.sendMove} />
);
}
}

View File

@ -16,16 +16,14 @@ class ChessBoardSquare extends React.Component {
}
selectSquare() {
const { piece, store } = this.props;
const { piece, store, sendMove } = this.props;
const { gameId, selectedSquare, player } = store.getState();
if (selectedSquare != null && this.moveIsValid()) {
API.updateGame(gameId, {
sendMove(gameId, {
from: selectedSquare,
to: this.squareCoords,
}).then((response) => {
store.dispatch(setGame(response.data));
});
})
} else if (selectedSquare != null) {
store.dispatch(selectPiece(null));
} else if (this.playerCanSelectPiece(player, piece)) {

View File

@ -3,30 +3,11 @@ import _ from "lodash";
import { connect } from "react-redux";
import classNames from "classnames";
import API from "../services/api";
import Channel from "../services/channel";
import { setPlayer, setGame, setGameId } from "../store/actions";
import ChessBoardSquare from "./chess-board-square";
class ChessBoard extends React.Component {
componentWillMount() {
const { gameId, store } = this.props;
store.dispatch(setGameId(gameId));
API.getGame(gameId)
.then(response => {
store.dispatch(setPlayer(response.data.player));
store.dispatch(setGame(response.data));
});
this.channel = Channel.gameChannel(gameId);
this.channel.on("game_update", data => {
store.dispatch(setGame(data));
});
}
getTurn() {
@ -45,7 +26,7 @@ class ChessBoard extends React.Component {
}
renderFiles(rankId) {
const { store } = this.props;
const { store, sendMove } = this.props;
const rank = this.getBoard()[rankId];
return _.map(this.files(rank), fileId => {
@ -56,6 +37,7 @@ class ChessBoard extends React.Component {
rank={rankId}
piece={rank[fileId]}
store={store}
sendMove={sendMove}
/>
);
});