I’m trying to update state, with an object of arrays, but it doesn’t update on first button click

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật