My current functional component is requiring me to press a button twice before it runs the nested if statement.
From my current understanding any change of state will re render the whole component, so I believe that is what is stopping the if statement to run straight away.
If that is the problem I am still unsure of how to solve it.
const [ inputData, setInputData ] = useState("Botany") // Example of state
const [ lockInputData, setLockInputData ] = useState("")
const [ prevLockInputData, setPrevLockInputData ] = useState("")
// Button element prop
inputDataSubmit={ () => submitData(inputData) } // On button press this will be called.
const submitData = async (inputData) => {
setLockInputData(inputData);
if (lockInputData !== "" && lockInputData !== prevLockInputData) {
await newCat(inputData.replace(/[" "]/g, "_"));
setPrevLockInputData(lockInputData);
} else if (lockInputData !== "" && lockInputData === prevLockInputData) {
await newSubCat(inputData.replace(/[" "]/g, "_"));
}
}
Component bit where inputDataSubmit is being used:
<form
onSubmit={ () => false}
>
<input
action=""
type="text"
placeholder="Category"
value={props.inputData}
onChange={props.handleChange}
/>
<button
type="button"
onClick={props.inputDataSubmit}
>
Random
</button>
</form>
Feel free to also provide suggestions on coding best practices.
inputDataSubmit?