Next.js Client Side Conditional State

I have a Next.js app with a client side part of the app. The form takes a min and max from the user. Using that, I render a form with (max - min) inputs. I validate the input for the max and min to make sure the (max - min) always returns a positive number. To render the form, I create a type using numberOfQuestions and create a React State.
const questionsSchema = numericEnum(Options)
.optional()
.array()
.length(numberOfQuestions)
const defaultState: z.infer<typeof questionsSchema> = Array(
numberOfQuestions,
).map((_) => undefined)
const [answers, setAnswers] =
useState<z.infer<typeof questionsSchema>>(defaultState)
const questionsSchema = numericEnum(Options)
.optional()
.array()
.length(numberOfQuestions)
const defaultState: z.infer<typeof questionsSchema> = Array(
numberOfQuestions,
).map((_) => undefined)
const [answers, setAnswers] =
useState<z.infer<typeof questionsSchema>>(defaultState)
This works fine in dev since previous validation makes sure the numbeOfQuestions is never NaN. However, when I try to next build, I guess next tries to run it and numberOfQuestions is NaN giving me an RangeError: Invalid array length. So now I decided return before this ^ if numberOfQuestions is NaN
if (typeof numberOfQuestions !== "number") {
return (
<div>
<p>Error: Max questions not greater than min questions.</p>
</div>
)
}
if (typeof numberOfQuestions !== "number") {
return (
<div>
<p>Error: Max questions not greater than min questions.</p>
</div>
)
}
However, this means I'm "conditionally setting state" which is not allowed. React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?eslintreact-hooks/rules-of-hooks https://reactjs.org/docs/hooks-rules.html Any ideas on how I can fix this?
Rules of Hooks – React
A JavaScript library for building user interfaces
0 Replies
No replies yetBe the first to reply to this messageJoin
Want results from more Discord servers?
Add your server