Skip to content

Commit

Permalink
persisting state + redirect to game if persisted state is availabel +…
Browse files Browse the repository at this point in the history
… restart action
  • Loading branch information
gustavfrid committed Nov 24, 2021
1 parent 88412d5 commit 7fe13d1
Show file tree
Hide file tree
Showing 8 changed files with 408 additions and 374 deletions.
637 changes: 319 additions & 318 deletions code/package-lock.json

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions code/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
"react-redux": "^7.2.6",
"react-router-dom": "^6.0.2",
"react-scripts": "^3.3.0",
"redux-thunk": "^2.4.0",
"styled-components": "^5.3.3",
"uniqid": "^5.4.0"
},
Expand Down
36 changes: 13 additions & 23 deletions code/src/App.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,35 @@
import React from 'react'
import { Provider } from 'react-redux'
import { combineReducers, configureStore } from '@reduxjs/toolkit' //createStore
import { BrowserRouter, Routes, Route } from 'react-router-dom'

import { game } from './reducers/game'
import { ui } from './reducers/ui'
import { setupStore } from './store/setupStore'
import { Header } from './components/Header'
import { StartPage } from './components/StartPage'
import { CurrentStep } from './components/CurrentStep'

const reducer = combineReducers({ game: game.reducer, ui: ui.reducer })
const store = configureStore({ reducer })

// Retrieve localstorage as initial state
// const persistedStateJSON = localStorage.getItem('gameReduxState')
// let persistedState = {}
const persistedStateJSON = localStorage.getItem('gameReduxState')
let persistedState = {}

// if (persistedStateJSON) {
// persistedState = JSON.parse(persistedStateJSON)
// }
if (persistedStateJSON) {
persistedState = JSON.parse(persistedStateJSON)
}

// Create store with initial state
// const store = createStore(
// reducer,
// persistedState,
// window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
// )
const store = setupStore(persistedState)

// Store the state in localstorage when Redux state change
// store.subscribe(() => {
// localStorage.setItem('gameReduxState', JSON.stringify(store.getState()))
// })
store.subscribe(() => {
localStorage.setItem('gameReduxState', JSON.stringify(store.getState()))
})

export const App = () => {
return (
<Provider store={store}>
<Header/>
<Header />
<BrowserRouter>
<Routes>
<Route path="/" element={<StartPage/>} />
<Route path="/game" element={<CurrentStep/>} />
<Route path='/' element={<StartPage />} />
<Route path='/game' element={<CurrentStep />} />
</Routes>
</BrowserRouter>
</Provider>
Expand Down
2 changes: 2 additions & 0 deletions code/src/components/CurrentStep.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { nextStep } from 'reducers/game'
import styled from 'styled-components'
import { useNavigate } from 'react-router-dom'

import { game } from '../reducers/game'
import { Loader } from './Loader'

const Container = styled.div`
Expand Down Expand Up @@ -61,6 +62,7 @@ export const CurrentStep = () => {
let navigate = useNavigate()

const onRestart = () => {
dispatch(game.actions.restartGame())
navigate('/')
}

Expand Down
60 changes: 33 additions & 27 deletions code/src/components/StartPage.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import React, { useState } from "react";
import { useDispatch } from "react-redux";
import { startGame } from "reducers/game";
import styled from "styled-components";
import { useNavigate } from "react-router-dom";
import React, { useState, useEffect } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { startGame } from 'reducers/game'
import styled from 'styled-components'
import { useNavigate } from 'react-router-dom'

import labyrith from "../images/labyrinth.jpg";
import labyrith from '../images/labyrinth.jpg'

const Container = styled.div`
display: flex;
Expand All @@ -14,48 +14,54 @@ const Container = styled.div`
width: 300px;
padding: 10px;
margin: 0 auto;
`;
`

const SmallHeader = styled.h2`
font-size: 15px;
`;
`

const Input = styled.input`
height: 30px;
width: 250px;
border-radius: 6px;
margin-bottom: 10px;
`;
text-align: center;
`

const Button = styled.button`
width: 130px;
height: 30px;
border-radius: 6px;
font-family: IBM Plex Mono;
font-weight: bold;
`;
`

const HeaderImage = styled.img`
width: 150px;
`;
`

export const StartPage = () => {
const dispatch = useDispatch();
let navigate = useNavigate();
// const username = useSelector(store => store.game.username)
const dispatch = useDispatch()
let navigate = useNavigate()
const username = useSelector(store => store.game.username)
const [input, setInput] = useState('')

const [input, setInput] = useState("");
useEffect(() => {
if (username !== '') {
navigate('/game')
}
}, [username, navigate])

const onStartGame = () => {
navigate("/game");
dispatch(startGame(input));
};
navigate('/game')
dispatch(startGame(input))
}

const onKeyDown = (e) => {
if (e.key === "Enter") {
onStartGame();
const onKeyDown = e => {
if (e.key === 'Enter') {
onStartGame()
}
};
}

return (
<div>
Expand All @@ -65,15 +71,15 @@ export const StartPage = () => {
<SmallHeader>What's your name?</SmallHeader>

<Input
type="text"
type='text'
value={input}
onChange={(e) => setInput(e.target.value)}
onChange={e => setInput(e.target.value)}
onKeyDown={onKeyDown}
/>
<Button disabled={input === ""} onClick={onStartGame}>
<Button disabled={input === ''} onClick={onStartGame}>
Start game!
</Button>
</Container>
</div>
);
};
)
}
17 changes: 11 additions & 6 deletions code/src/reducers/game.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,15 @@ import uniqid from 'uniqid'

import { ui } from './ui'

const initialState = {
username: '',
currentStep: {},
steps: [],
}

export const game = createSlice({
name: 'game',
initialState: {
username: '',
currentStep: {},
steps: [],
},
initialState,
reducers: {
createUser: (store, action) => {
store.username = action.payload
Expand All @@ -19,7 +21,10 @@ export const game = createSlice({
},
setSteps: (store, action) => {
const newSteps = [...store.steps, action.payload]
store.steps = [...newSteps]
store.steps = [...newSteps]
},
restartGame: () => {
return initialState
},
},
})
Expand Down
6 changes: 6 additions & 0 deletions code/src/reducers/rootReducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { combineReducers } from '@reduxjs/toolkit'

import { game } from './game'
import { ui } from './ui'

export const rootReducer = combineReducers({ game: game.reducer, ui: ui.reducer })
23 changes: 23 additions & 0 deletions code/src/store/setupStore.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { applyMiddleware, compose, createStore } from '@reduxjs/toolkit'
import thunkMiddleware from 'redux-thunk'

import { rootReducer } from 'reducers/rootReducer'

export const setupStore = preloadedState => {
const middlewares = [thunkMiddleware]
const middlewareEnhancer = applyMiddleware(...middlewares)

const enhancers = [
middlewareEnhancer,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__(),
]
const composedEnhancers = compose(...enhancers)

const store = createStore(rootReducer, preloadedState, composedEnhancers)

// if (process.env.NODE_ENV !== 'production' && module.hot) {
// module.hot.accept('./reducers', () => store.replaceReducer(rootReducer))
// }

return store
}

0 comments on commit 7fe13d1

Please sign in to comment.