Created
April 26, 2020 21:22
-
-
Save jensen/3fcc5457c60bf6ea4733424f70536ce5 to your computer and use it in GitHub Desktop.
Word game reducer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState, useEffect, useReducer } from "react"; | |
import Word from "./components/Word"; | |
import wordsLibrary from "./words"; | |
const starsSpeed = { animation: "animStar 50s linear infinite" }; | |
const reducer = (state, action) => { | |
const { type, payload } = action; | |
if (type === "addWord") { | |
return { | |
...state, | |
words: [ | |
...state.words, | |
wordsLibrary[Math.floor(Math.random() * wordsLibrary.length)] | |
] | |
}; | |
} | |
if (type === "updateInput") { | |
const index = state.words.indexOf(payload); | |
if (index > -1) { | |
return { | |
...state, | |
words: [ | |
...state.words.slice(0, index), | |
"", | |
...state.words.slice(index + 1) | |
], | |
inputValue: "" | |
}; | |
} | |
return { | |
...state, | |
inputValue: payload | |
}; | |
} | |
}; | |
const App = () => { | |
// states | |
// const [inputValue, setInputValue] = useState(""); | |
const [state, dispatch] = useReducer(reducer, { | |
words: [], | |
inputValue: "" | |
}); | |
// hooks | |
useEffect(() => { | |
// console.log(wordsLibrary); | |
const addWord = () => { | |
dispatch({ | |
type: "addWord" | |
}); | |
setTimeout(addWord, 1.5 * 1000); | |
}; | |
addWord(); | |
}, []); | |
// useEffect(() => { | |
// let findWordIndex = words.findIndex(el => el === inputValue); | |
// if (findWordIndex > -1) { | |
// dispatch({ type: "removeWord", payload: inputValue }); | |
// } | |
// }, [inputValue, words]); | |
const handleInputChange = e => { | |
dispatch({ type: "updateInput", payload: e.target.value.trim() }); | |
e.target.placeholder = ""; | |
}; | |
// jsx | |
return ( | |
<> | |
{state.words.map((el, index) => ( | |
<Word key={index} value={el} /> | |
))} | |
<div className="score">Score: 2630</div> | |
<div style={starsSpeed} id="stars" /> | |
<div className="input-group"> | |
<input | |
autoFocus | |
value={state.inputValue} | |
onChange={e => handleInputChange(e)} | |
type="input" | |
placeholder="Type here..." | |
className="input" | |
id="name" | |
autoComplete="off" | |
/> | |
</div> | |
</> | |
); | |
}; | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment