0

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.

2
  • May you also share where you are using inputDataSubmit? Commented Jul 5, 2020 at 22:13
  • Alright, I've added that bit too. Commented Jul 5, 2020 at 23:53

1 Answer 1

1

I think because setState could be asynchronous (and setLockInputData is a setState).

You could try:

const submitData = async (inputData) => {
  setLockInputData(inputData);

  if(inputData !== "") {
    if(inputData !== prevLockInputData) {
      await newCat(inputData.replace(/[" "]/g, "_"));
      setPrevLockInputData(inputData);
    }
    else
      await newSubCat(inputData.replace(/[" "]/g, "_"));
  }
}

Hope this helps.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.