Add sample for useReduceer

This commit is contained in:
2023-11-10 17:23:38 +07:00
parent 53c6727f2b
commit 5addb2fc63
25 changed files with 19205 additions and 0 deletions
+23
View File
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies
/node_modules
/.pnp
.pnp.js
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
+70
View File
@@ -0,0 +1,70 @@
# Getting Started with Create React App
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).
## Available Scripts
In the project directory, you can run:
### `npm start`
Runs the app in the development mode.\
Open [http://localhost:3000](http://localhost:3000) to view it in your browser.
The page will reload when you make changes.\
You may also see any lint errors in the console.
### `npm test`
Launches the test runner in the interactive watch mode.\
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.
### `npm run build`
Builds the app for production to the `build` folder.\
It correctly bundles React in production mode and optimizes the build for the best performance.
The build is minified and the filenames include the hashes.\
Your app is ready to be deployed!
See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.
### `npm run eject`
**Note: this is a one-way operation. Once you `eject`, you can't go back!**
If you aren't satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.
Instead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you're on your own.
You don't have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn't feel obligated to use this feature. However we understand that this tool wouldn't be useful if you couldn't customize it when you are ready for it.
## Learn More
You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).
To learn React, check out the [React documentation](https://reactjs.org/).
### Code Splitting
This section has moved here: [https://facebook.github.io/create-react-app/docs/code-splitting](https://facebook.github.io/create-react-app/docs/code-splitting)
### Analyzing the Bundle Size
This section has moved here: [https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size](https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size)
### Making a Progressive Web App
This section has moved here: [https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app](https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app)
### Advanced Configuration
This section has moved here: [https://facebook.github.io/create-react-app/docs/advanced-configuration](https://facebook.github.io/create-react-app/docs/advanced-configuration)
### Deployment
This section has moved here: [https://facebook.github.io/create-react-app/docs/deployment](https://facebook.github.io/create-react-app/docs/deployment)
### `npm run build` fails to minify
This section has moved here: [https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify](https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify)
+139
View File
@@ -0,0 +1,139 @@
{
"questions": [
{
"question": "Which is the most popular JavaScript framework?",
"options": ["Angular", "React", "Svelte", "Vue"],
"correctOption": 1,
"points": 10
},
{
"question": "Which company invented React?",
"options": ["Google", "Apple", "Netflix", "Facebook"],
"correctOption": 3,
"points": 10
},
{
"question": "What's the fundamental building block of React apps?",
"options": ["Components", "Blocks", "Elements", "Effects"],
"correctOption": 0,
"points": 10
},
{
"question": "What's the name of the syntax we use to describe the UI in React components?",
"options": ["FBJ", "Babel", "JSX", "ES2015"],
"correctOption": 2,
"points": 10
},
{
"question": "How does data flow naturally in React apps?",
"options": [
"From parents to children",
"From children to parents",
"Both ways",
"The developers decides"
],
"correctOption": 0,
"points": 10
},
{
"question": "How to pass data into a child component?",
"options": ["State", "Props", "PropTypes", "Parameters"],
"correctOption": 1,
"points": 10
},
{
"question": "When to use derived state?",
"options": [
"Whenever the state should not trigger a re-render",
"Whenever the state can be synchronized with an effect",
"Whenever the state should be accessible to all components",
"Whenever the state can be computed from another state variable"
],
"correctOption": 3,
"points": 30
},
{
"question": "What triggers a UI re-render in React?",
"options": [
"Running an effect",
"Passing props",
"Updating state",
"Adding event listeners to DOM elements"
],
"correctOption": 2,
"points": 20
},
{
"question": "When do we directly \"touch\" the DOM in React?",
"options": [
"When we need to listen to an event",
"When we need to change the UI",
"When we need to add styles",
"Almost never"
],
"correctOption": 3,
"points": 20
},
{
"question": "In what situation do we use a callback to update state?",
"options": [
"When updating the state will be slow",
"When the updated state is very data-intensive",
"When the state update should happen faster",
"When the new state depends on the previous state"
],
"correctOption": 3,
"points": 30
},
{
"question": "If we pass a function to useState, when will that function be called?",
"options": [
"On each re-render",
"Each time we update the state",
"Only on the initial render",
"The first time we update the state"
],
"correctOption": 2,
"points": 30
},
{
"question": "Which hook to use for an API request on the component's initial render?",
"options": ["useState", "useEffect", "useRef", "useReducer"],
"correctOption": 1,
"points": 10
},
{
"question": "Which variables should go into the useEffect dependency array?",
"options": [
"Usually none",
"All our state variables",
"All state and props referenced in the effect",
"All variables needed for clean up"
],
"correctOption": 2,
"points": 30
},
{
"question": "An effect will always run on the initial render.",
"options": [
"True",
"It depends on the dependency array",
"False",
"In depends on the code in the effect"
],
"correctOption": 0,
"points": 30
},
{
"question": "When will an effect run if it doesn't have a dependency array?",
"options": [
"Only when the component mounts",
"Only when the component unmounts",
"The first time the component re-renders",
"Each time the component is re-rendered"
],
"correctOption": 3,
"points": 20
}
]
}
File diff suppressed because it is too large Load Diff
+40
View File
@@ -0,0 +1,40 @@
{
"name": "useReducer-app",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^5.17.0",
"@testing-library/react": "^13.4.0",
"@testing-library/user-event": "^13.5.0",
"json-server": "^0.17.4",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"server": "json-server --watch data/questions.json --port 8080"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 3.8 KiB

+43
View File
@@ -0,0 +1,43 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="icon" href="%PUBLIC_URL%/favicon.ico" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="theme-color" content="#000000" />
<meta
name="description"
content="Web site created using create-react-app"
/>
<link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" />
<!--
manifest.json provides metadata used when your web app is installed on a
user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json" />
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
Binary file not shown.

After

Width:  |  Height:  |  Size: 5.2 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 9.4 KiB

@@ -0,0 +1,25 @@
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
},
{
"src": "logo192.png",
"type": "image/png",
"sizes": "192x192"
},
{
"src": "logo512.png",
"type": "image/png",
"sizes": "512x512"
}
],
"start_url": ".",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
+3
View File
@@ -0,0 +1,3 @@
# https://www.robotstxt.org/robotstxt.html
User-agent: *
Disallow:
+121
View File
@@ -0,0 +1,121 @@
import { useEffect, useReducer } from "react";
import Header from "./Header";
import Main from "./Main";
import Loader from "./Loader";
import Error from "./Error";
import StarScreen from "./StarScreen";
import Questions from "./Questions";
import NextButton from "./NextButton";
import Progress from "./Progress";
import FinishScreen from "./FinishScreen";
const initialState = {
questions: [],
// 'loading', 'error', 'ready', 'active', 'finished'
status: "loading",
index: 0,
answer: null,
points: 0,
highscore: 0,
};
const reducer = (state, action) => {
switch (action.type) {
case "dataReceived":
return {
...state,
questions: action.payload,
status: "ready",
};
case "dataFailed":
return {
...state,
status: "error",
};
case "start":
return { ...state, status: "active" };
case "newAnswer":
const question = state.questions.at(state.index);
return {
...state,
answer: action.payload,
points:
action.payload === question.correctOption
? state.points + question.points
: state.points,
};
case "nextQuestion":
return { ...state, index: state.index + 1, answer: null };
case "finish":
return {
...state,
status: "finished",
highscore:
state.points > state.highscore ? state.points : state.highscore,
};
default:
throw new Error("Action unknown");
}
};
export default function App() {
const [{ questions, status, index, answer, points, highscore }, dispatch] =
useReducer(reducer, initialState);
const numQuestions = questions.length;
const maxPossiblePoints = questions.reduce(
(prev, cur) => prev + cur.points,
0
);
useEffect(() => {
fetch("http://localhost:8080/questions")
.then((res) => res.json())
.then((data) => dispatch({ type: "dataReceived", payload: data }))
.catch((err) => dispatch({ type: "dataFailed" }));
}, []);
return (
<div className="app">
<Header />
<Main>
{status === "loading" && <Loader />}
{status === "error" && <Error />}
{status === "ready" && (
<StarScreen numQuestions={numQuestions} dispatch={dispatch} />
)}
{status === "active" && (
<>
<Progress
index={index}
numQuestions={numQuestions}
points={points}
maxPossiblePoints={maxPossiblePoints}
answer={answer}
/>
<Questions
question={questions[index]}
dispatch={dispatch}
answer={answer}
/>
<NextButton
dispatch={dispatch}
answer={answer}
numQuestions={numQuestions}
index={index}
/>
</>
)}
{status === "finished" && (
<FinishScreen
points={points}
maxPossiblePoints={maxPossiblePoints}
highscore={highscore}
/>
)}
</Main>
</div>
);
}
@@ -0,0 +1,79 @@
import { useReducer } from "react";
const initialState = { count: 0, step: 1 };
function reducer(state, action) {
console.log(state, action);
switch (action.type) {
case "dec":
return { ...state, count: state.count - state.step };
case "inc":
return { ...state, count: state.count + state.step };
case "setCount":
return { ...state, count: action.payload };
case "setStep":
return { ...state, step: action.payload };
case "reset":
return initialState;
default:
throw new Error("Unknown action!");
}
}
function DateCounter() {
const [state, dispatch] = useReducer(reducer, initialState);
const { count, step } = state;
// This mutates the date object.
const date = new Date("june 21 2027");
date.setDate(date.getDate() + count);
const dec = function () {
dispatch({ type: "dec" });
};
const inc = function () {
dispatch({ type: "inc" });
};
const defineCount = function (e) {
dispatch({ type: "setCount", payload: Number(e.target.value) });
};
const defineStep = function (e) {
dispatch({ type: "setStep", payload: Number(e.target.value) });
};
const reset = function () {
dispatch({ type: "reset" });
};
return (
<div className="counter">
<div>
<input
type="range"
min="0"
max="10"
value={step}
onChange={defineStep}
/>
<span>{step}</span>
</div>
<div>
<button onClick={dec}>-</button>
<input value={count} onChange={defineCount} />
<button onClick={inc}>+</button>
</div>
<p>{date.toDateString()}</p>
<div>
<button onClick={reset}>Reset</button>
</div>
</div>
);
}
export default DateCounter;
@@ -0,0 +1,9 @@
function Error() {
return (
<p className="error">
<span>💥</span> There was an error fecthing questions.
</p>
);
}
export default Error;
@@ -0,0 +1,15 @@
function FinishScreen({ points, maxPossiblePoints, highscore }) {
const percentage = (points / maxPossiblePoints) * 100;
return (
<>
<p className="result">
Your scored <strong>{points}</strong> out of {maxPossiblePoints} ({" "}
{Math.ceil(percentage)}%)
</p>
<p className="highscore">(Highscore: {highscore} points)</p>
</>
);
}
export default FinishScreen;
@@ -0,0 +1,10 @@
function Header() {
return (
<header className='app-header'>
<img src='logo512.png' alt='React logo' />
<h1>The React Quiz</h1>
</header>
);
}
export default Header;
@@ -0,0 +1,8 @@
export default function Loader() {
return (
<div className="loader-container">
<div className="loader"></div>
<p>Loading questions...</p>
</div>
);
}
@@ -0,0 +1,5 @@
function Main({ children }) {
return <main className="main">{children}</main>;
}
export default Main;
@@ -0,0 +1,25 @@
function NextButton({ dispatch, answer, index, numQuestions }) {
if (answer === null) return null;
if (index < numQuestions - 1)
return (
<button
className="btn btn-ui"
onClick={() => dispatch({ type: "nextQuestion" })}
>
Next
</button>
);
if (index === numQuestions - 1)
return (
<button
className="btn btn-ui"
onClick={() => dispatch({ type: "finish" })}
>
Finish
</button>
);
}
export default NextButton;
@@ -0,0 +1,26 @@
function Options({ question, dispatch, answer }) {
const hasAnswered = answer !== null;
return (
<div className="options">
{question.options.map((option, index) => (
<button
className={`btn btn-option ${index === answer ? "answer" : ""} ${
hasAnswered
? index === question.correctOption
? "correct"
: "wrong"
: ""
}`}
key={option}
disabled={hasAnswered}
onClick={() => dispatch({ type: "newAnswer", payload: index })}
>
{option}
</button>
))}
</div>
);
}
export default Options;
@@ -0,0 +1,16 @@
function Progress({ index, numQuestions, points, maxPossiblePoints, answer }) {
return (
<header className="progress">
<progress max={numQuestions} value={index + Number(answer !== null )} />
<p>
Questions <strong>{index + 1}</strong> / {numQuestions}
</p>
<p>
<strong>{points}</strong> / {maxPossiblePoints}
</p>
</header>
);
}
export default Progress;
@@ -0,0 +1,13 @@
import Options from "./Options";
function Questions({ question, dispatch, answer }) {
return (
<div>
<h4>{question.question}</h4>
<Options question={question} dispatch={dispatch} answer={answer} />
</div>
);
}
export default Questions;
@@ -0,0 +1,16 @@
function StarScreen({ numQuestions, dispatch }) {
return (
<div className="start">
<h2>Welcome to The React Quiz!</h2>
<h3>{numQuestions} questions to test your React mastery</h3>
<button
className="btn btn-ui"
onClick={() => dispatch({ type: "start" })}
>
Let's start!
</button>
</div>
);
}
export default StarScreen;
+259
View File
@@ -0,0 +1,259 @@
:root {
--color-darkest: #343a40;
--color-dark: #495057;
--color-medium: #ced4da;
--color-light: #f1f3f5;
--color-theme: #1098ad;
--color-accent: #ffa94d;
}
@import url("https://fonts.googleapis.com/css2?family=Codystar&display=swap");
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html {
font-size: 62.5%;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen,
Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif;
}
body {
min-height: 100vh;
color: var(--color-light);
background-color: var(--color-darkest);
padding: 3.2rem;
}
.app {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
}
.main {
width: 50rem;
}
.app-header {
width: 66rem;
margin-bottom: 4rem;
display: flex;
align-items: center;
justify-content: space-between;
}
.error {
text-align: center;
font-size: 1.6rem;
font-weight: 500;
padding: 2rem;
background-color: #495057;
border-radius: 100px;
}
img {
width: 14rem;
}
h1 {
font-family: "Codystar";
font-size: 5.6rem;
}
h2 {
font-size: 3.6rem;
margin-bottom: 2rem;
}
h3 {
font-size: 2.4rem;
font-weight: 600;
margin-bottom: 4rem;
}
h4 {
font-size: 2.2rem;
font-weight: 600;
margin-bottom: 2.4rem;
}
.start {
display: flex;
flex-direction: column;
align-items: center;
}
.progress {
margin-bottom: 4rem;
display: grid;
justify-content: space-between;
gap: 1.2rem;
grid-template-columns: auto auto;
font-size: 1.8rem;
color: var(--color-medium);
}
progress {
-webkit-appearance: none;
width: 100%;
height: 12px;
grid-column: 1 / -1;
}
::-webkit-progress-bar {
background-color: var(--color-medium);
border-radius: 100px;
}
::-webkit-progress-value {
background-color: var(--color-theme);
border-radius: 100px;
}
.btn {
display: block;
font-family: inherit;
color: inherit;
font-size: 2rem;
border: 2px solid var(--color-dark);
background-color: var(--color-dark);
padding: 1.2rem 2.4rem;
cursor: pointer;
border-radius: 100px;
transition: 0.3s;
}
.btn:not([disabled]):hover {
background-color: var(--color-darkest);
}
.btn-option:not([disabled]):hover {
transform: translateX(1.2rem);
}
.btn[disabled]:hover {
cursor: not-allowed;
}
.btn-ui {
float: right;
}
.options {
display: flex;
flex-direction: column;
gap: 1.2rem;
margin-bottom: 3.2rem;
}
.btn-option {
width: 100%;
text-align: left;
}
.btn-option.correct {
background-color: var(--color-theme);
border: 2px solid var(--color-theme);
color: var(--color-light);
}
.btn-option.wrong {
background-color: var(--color-accent);
border: 2px solid var(--color-accent);
color: var(--color-darkest);
}
.answer {
transform: translateX(2rem);
}
.result {
background-color: var(--color-theme);
color: var(--color-light);
border-radius: 100px;
text-align: center;
padding: 2rem 0;
font-size: 2rem;
font-weight: 500;
margin-bottom: 1.6rem;
}
.result span {
font-size: 2.2rem;
margin-right: 4px;
}
.highscore {
font-size: 1.8rem;
text-align: center;
margin-bottom: 4.8rem;
}
.loader-container {
display: flex;
flex-direction: column;
align-items: center;
margin-top: 4rem;
gap: 1.6rem;
color: var(--color-medium);
font-size: 1.4rem;
}
.timer {
float: left;
font-size: 1.8rem;
color: var(--color-medium);
border: 2px solid var(--color-dark);
padding: 1.35rem 2.8rem;
border-radius: 100px;
}
/* CREDIT: https://dev.to/afif/i-made-100-css-loaders-for-your-next-project-4eje */
.loader {
width: 50px;
height: 24px;
background: radial-gradient(circle closest-side, currentColor 90%, #0000) 0%
50%,
radial-gradient(circle closest-side, currentColor 90%, #0000) 50% 50%,
radial-gradient(circle closest-side, currentColor 90%, #0000) 100% 50%;
background-size: calc(100% / 3) 12px;
background-repeat: no-repeat;
animation: loader 1s infinite linear;
}
@keyframes loader {
20% {
background-position: 0% 0%, 50% 50%, 100% 50%;
}
40% {
background-position: 0% 100%, 50% 0%, 100% 50%;
}
60% {
background-position: 0% 50%, 50% 100%, 100% 0%;
}
80% {
background-position: 0% 50%, 50% 50%, 100% 100%;
}
}
/* ********** */
/* First counter example */
.counter {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
font-size: 2rem;
font-weight: bold;
margin: 6rem;
}
.counter * {
font-size: inherit;
padding: 0.8rem;
}
+11
View File
@@ -0,0 +1,11 @@
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './components/App';
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);