This is a bit of a long but here goes. I’m currently learning about hooks and reducer functions and am using it as an opportunity to build a rough quiz app that utilizes api calls, hooks, reducers and reducer hooks. I am aware that this is probably designed poorly at the moment, and could probably be fixed with the context api, however I am intent on understanding what I am building and as a result am trying to complete the task without using them (as they are also on my to learn list).
From the get go I have build a reducer hook, this holds my initial state, and my reducer functionality:
import { useReducer } from "react";
const initialreducerState = {
amount: "10",
category: "",
difficulty: "",
type: "multiple",
};
function reducer(reducerState, action) {
switch (action.type) {
case "setAmount":
return { ...reducerState, amount: action.payload };
case "setCategory":
return { ...reducerState, category: action.payload };
case "setDifficulty":
return { ...reducerState, difficulty: action.payload };
default:
throw new Error("Unknown action");
}
}
export default function useQuestionData() {
const [reducerState, dispatch] = useReducer(reducer, initialreducerState);
const defineAmount = function (e) {
dispatch({ type: "setAmount", payload: Number(e.target.value) });
};
const defineCategory = function (e) {
dispatch({ type: "setCategory", payload: e.value });
};
const defineDifficulty = function (e) {
dispatch({ type: "setDifficulty", payload: e.value });
};
const actions = {
defineAmount,
defineCategory,
defineDifficulty,
};
return { reducerState, actions };
This is then passed into my APP component, which distributes the reducerState and the actions to where they need to go:
export default function App() {
const [params, setParams] = useState();
const [questions, setQuestions] = useState();
const [start, setStart] = useState(false);
const { reducerState, actions } = useQuestionData();
const { questionData, isLoading, error } = useTrivia(params);
function handleSetStart() {
setParams(reducerState);
if (!questionData) {
return;
} else {
setQuestions((questions) =>
questionData.map((question) => {
return {
question: question.question,
correct: question.correct_answer,
incorrect: question.incorrect_answers,
points: 10,
};
})
);
setStart(!start);
}
}
return (
<div>
<Header />
<Debug reducerState={reducerState} start={start} />
{!start ? (
<GetQuestionData
actions={actions}
setStart={setStart}
start={start}
handleSetStart={handleSetStart}
/>
) : (
<Main questions={questions} />
)}
</div>
);
}
From here the actions are passed to the GetQuestionData which is used to get the button clicks and drop down elements, which then updates the reducer state with the users options.
export function GetQuestionData({ actions, handleSetStart }) {
return (
<div className="quiz-selection">
<p>Number Of Questions</p>
<div className="quiz-buttons">
<span>
<button value="10" onClick={actions.defineAmount}>
10
</button>
</span>
<span>
<button value="20" onClick={actions.defineAmount}>
20
</button>
</span>
<span>
<button value="30" onClick={actions.defineAmount}>
30
</button>
</span>
<span>
<button value="40" onClick={actions.defineAmount}>
40
</button>
</span>
<span>
<button value="50" onClick={(e) => actions.defineAmount(e)}>
50
</button>
</span>
</div>
<div className="select">
<p className="cat-header">Category</p>
<Select onChange={actions.defineCategory} options={category_options} />
<p className="cat-header">Difficulty</p>
<Select
onChange={actions.defineDifficulty}
options={difficulty_options}
/>
</div>
<div>
<button className="quiz-buttons" onClick={() => handleSetStart()}>
Start
</button>
</div>
</div>
);
}
I save the user options into state (for passing into my trivia hook, then send them there and get the API data back)
export function useTrivia(query) {
const [questionData, setQuestionData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState("");
useEffect(
function () {
if (query === undefined) {
console.log("no query");
} else {
const controller = new AbortController();
async function fetchQuestions() {
try {
setIsLoading(true);
setError("");
const res = await fetch(
`https://opentdb.com/api.php?amount=${query.amount}&category=${query.category}&difficlty=${query.difficulty}&type=multiple`,
{ signal: controller.signal }
);
console.log(res);
if (!res.ok) throw new Error("Trivia Fetching Failed");
const data = await res.json();
if (data.response === "False")
throw new Error("Questions Not Found");
setQuestionData(data.results);
setError("");
} catch (err) {
if (err.name !== "AbortError") {
setError(err.message);
}
} finally {
setIsLoading(false);
}
}
fetchQuestions();
return function () {
controller.abort();
};
}
},
[query]
);
return { questionData, isLoading, error };
}
This is where my problem arises, or at least my two part problem. Firstly the data that I get back is an array of objects, I kind of figure this is due to the data from the API. The second problem and why I am here is that i’m unsure why but my state doesn’t update onClick of the start button in my getQuestionData. The code works but only after I click 2-3 times.
I thought it was something to do with the state updates so I followed some of the similar questions on here like changing my state setup to be like
setState((prevState) => prevState, newState)
but to no avail, I also started running into undefined errors which im using guard clauses and early returns to circumvent now for testing.
SO heres my question, where in my code am I missing something? I feel like im following the rules somewhat accurately and have tried several solutions but Im not making any progress.
Any help or advice would be appreciated, also apologies for the long post I want to be as detailed as possible
Also for clarification the options objects im importing are setup like this:
export const category_options = [
{ value: "9", label: "General Knowledge" },
{ value: "10", label: "Entertainment: Books" },
{ value: "11", label: "Entertainment: Film" },
{ value: "12", label: "Entertainment: Music" },
Ill edit the post as needed with additional context