Search code examples
reactjsuse-state

Disable submit button if element found in array in react


I want to disable the submit button on the form if the user enters a value that already exists in the task list. 'Todos' is the array that stores the list and I used 'some' to check if the input value is equal to some title. However, it doesn't work.

CODE

const [disable, setDisable] = useState(false);
const onFormSubimit = (event) => {
        event.preventDefault();
        if (!editTodo) { //mudar depois a condição
            setTodos([...todos, {
                id: uuidv4(),
                title: input,
                completed: false
            }]);
            setInput("");
        } else {
            updateTodo(input, editTodo.id, editTodo.completed);
        }
    }
    const handleInputChange = (event) => {
        let inputValue = event.target.value;
        setInput(inputValue);
        getInputValue(inputValue);
    }
    const getInputValue = (inputValue) => {
        let some = todos.some(item => item.title === inputValue);
        if (some!=disable) {
           setDisable(true);
        }
    }
    return (
        <form onSubmit={onFormSubimit}>
            <input type='text' name='text' placeholder='Insira o nome da tarefa' className='task-input' value={input} onChange={handleInputChange} required></input>
            <button type='submit' className='button-add' disabled={getInputValue} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
        </form>
    );
}


Solution

  • Your button state is dependent on input (the variable set by setInput) and todos. So the best way to handle this is via an useEffect with a dependency array.

    useEffect(() => {
      // Array.some returns a boolean
      setDisable(todos.some(item => item.title === input))
    }, [todos, input]);
    

    Your button code

    <button type='submit' className='button-add' disabled={disable} >{editTodo ? 'Alterar' : 'Adicionar'}</button>
    

    You can also directly use this logic in button like below. In this case there is no need of useEffect

    <button type='submit' className='button-add' disabled={todos.some(item => item.title === input)} >{editTodo ? 'Alterar' : 'Adicionar'}</button>