Skip to content

Instantly share code, notes, and snippets.

@newbornfrontender
Created October 5, 2019 16:34
Show Gist options
  • Save newbornfrontender/02868d5cf5300b1715be3447009e6c91 to your computer and use it in GitHub Desktop.
Save newbornfrontender/02868d5cf5300b1715be3447009e6c91 to your computer and use it in GitHub Desktop.
Redirect example
import React from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';
import { Row } from './Row';
import { createTable } from '../helpers';
export const Table: React.FC = () => {
const url = 'http://localhost:5000';
const initialTable = createTable(6, 7);
const [table, setTable] = React.useState<number[][]>(initialTable);
React.useEffect(() => {
// Hack: setInterval(() => { /* axios code */ }, 2000);
axios.get(`${url}/`).then(({ data }) => setTable(data.table));
}, []);
const [currentUser, setCurrentUser] = React.useState<number>(1);
const changeCurrentUser = () => (currentUser === 1 ? setCurrentUser(2) : setCurrentUser(1));
const [winner, setWinner] = React.useState<number | string>(0);
const handleRowClick = (index: number) => {
if (!winner) {
changeCurrentUser();
const data = {
table,
columnIndex: index,
currentUser,
};
axios.post(`${url}/move`, data).then(({ data }) => {
setTable(data.table);
setWinner(data.winner);
});
}
};
if (winner) {
return <Redirect to="/" />
}
return (
<>
<p>{winner}</p>
<table>
<tbody>
{table.map((row: number[], i: number) => (
<Row onRowClick={() => handleRowClick(i)} row={row} key={i} />
))}
</tbody>
</table>
<style jsx>{`
table {
border-collapse: collapse;
}
tbody {
display: flex;
padding: 0.6rem;
border: 1px solid black;
border-radius: 20px;
background-color: papayawhip;
}
`}</style>
</>
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment