State Management With Vanilla JavaScript
One of the biggest hurdles one has to cross when creating applications with vanilla JavaScript is maintaining the state of information that is relevant to your application while a user interacts with it.
My Application
In my Bulletin Board web application there are are many different “bulletins” that can be selected by a user, and based off the users selection, “bulletin boards” will be displayed that belong to that specific bulletin. (sorry for the excessive use of the word bulletin)
This was fairly straight forward. All that I needed to do was add an event listener to the input of the dropdown and collect the value of the target element — which contains the id of the bulletin.
I would then pass that id to a fetch function. This would get the data concerning the selected bulletin and then append all of the bulletin boards associated with it. Simple.
But now I wanted to have the functionality to add new items to a specific board. This was not as easy.
The Problem
Each bulletin board card has on it a + icon for adding new items — and on a click event of that + icon a modal would pop up with a form to create a new item.
But for the life of me I could not figure out how to pass data from the bulletin board card to the form in order to let the form know which bulletin board card to create an association of the new item with and where to append the information.
I settled on this…
My Solution
On creation of the new bulletin board card, wether on the first page load or on the creation of a new board using AJAX, I would add an id to the + icon that would be clicked, so I could access it with
event.target
this would allow me to access the attributes that are associated with that event.
However I still needed to pass this data to the AJAX ‘POST’ request in order to know what endpoint to make this request to and which bulletin board to associate this new item with.
I created a custom attribute for the form in the modal that initially does not have any value— only on pop up of the modal with the + icon click event does it get a value. This value is taken from the + icon and corresponds to the unique id of the bulletin board card.
Once passed to the AJAX request, the data is persisted and the board is then re-rendered with the new item.