Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Issue #7] - Automatically fetch call results #23

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 33 additions & 4 deletions src/Components/WordAPI.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import React from "react";
import React, { useState, useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { motion } from "framer-motion";
import { useRef } from "react";
Expand All @@ -10,11 +10,11 @@ import {
} from "../Utils/getRandomParagraph";

export default function WordAPI() {
const paragraph = getRandomParagraph();
const [paragraph, setParagraph] = useState(getRandomParagraph()); // Initialize paragraph once
const inputRef = useRef(null);
const [inputText, setInputText] = useState("");

const handleAccuracy = () => {
const inputText = inputRef.current.value;
const { totalAccurateWords } = getStatistics(inputText, paragraph);
const userAccuracy = Math.floor(
(totalAccurateWords / PARAGRAPH_LENGTH) * 100
Expand All @@ -24,11 +24,34 @@ export default function WordAPI() {
};

const navigate = useNavigate();

const buttonHandler = () => {
const userAccuracy = handleAccuracy();
navigate("/results", { state: { userAccuracy } });
};

const handleInputChange = (e) => {
const text = e.target.value;
setInputText(text);
};

const handleKeyDown = (e) => {
if (e.key === " " || e.key === "Enter") {
// Check for last word here
const words = inputText.trim().split(" ");
if (words.length >= PARAGRAPH_LENGTH) {
buttonHandler();
}
}
};

useEffect(() => {
console.log("WordAPI component mounted");
return () => {
console.log("WordAPI component unmounted");
};
}, []);

return (
<>
<motion.div
Expand All @@ -38,7 +61,13 @@ export default function WordAPI() {
>
<div className="textHolder">
<textarea className="fetchText" placeholder={paragraph} readOnly />
<textarea className="fetchTextOverlay" ref={inputRef}></textarea>
<textarea
className="fetchTextOverlay"
ref={inputRef}
value={inputText}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
></textarea>
<button onClick={buttonHandler} className="accuracy">
ACCURACY
</button>
Expand Down