import IdeasApi from '../services/ideasApi'; import IdeaList from './IdeaList'; class IdeaForm { constructor() { this._formModal = document.querySelector('#form-modal'); //instantiating the idea list since it is a class this._ideaList = new IdeaList(); } //add all event listeners in a function addEventListeners() { this._form.addEventListener('submit', this.handleSubmit.bind(this)); } async handleSubmit(e) { //made this function async because we are dealing with a promise (axios) e.preventDefault(); //stops the submit and allows us to determine when it should run if ( !this._form.elements.text.value || !this._form.elements.tag.value || !this._form.elements.username.value ) { alert('Please enter all fields'); return; } //save user to local storage localStorage.setItem('username', this._form.elements.username.value); //grabs values from the form const idea = { text: this._form.elements.text.value, tag: this._form.elements.tag.value, username: this._form.elements.username.value, }; //add idea to database const newIdea = await IdeasApi.createIdea(idea); //add idea to list and call render on the DOM this._ideaList.addIdeaToList(newIdea.data.data_base); //clear form fields after submit this._form.elements.text.value = ''; this._form.elements.tag.value = ''; this._form.elements.username.value = ''; this.render(); //using the dispatch event method of the document object to dispatch a custom event //to the Modal from the IdeaForm, telling the Modal to close the form on submit document.dispatchEvent(new Event('closemodal')); } //create a render function like react that will output the HTML //adding a turnary to check for username and saved in localstorage render() { this._formModal.innerHTML = `
`; this._form = document.querySelector('#idea-form'); this.addEventListeners(); //added within the render function because the HTML above is only available //in the DOM after the render function is called. } } export default IdeaForm;