Using a Checkbox To Instantly Refresh Page With New Data

Ivan Luk
Level Up Coding
Published in
3 min readNov 10, 2020

--

In this blog, I will go through how to use a checkbox to quickly refresh a page with new data. This page by default displays all the foursomes created by different users. Each foursome was tagged with a handicap number as an indicator to other golfers the skill level expected if he/she wants to play in this foursome. Each user can enter his or her own handicap on the profile page once signed up. The following shows the behavior of the page when the checkbox is checked or unchecked.

To accomplish this we need to have a setup that the display of the foursome cards is tied to the checkbox action. For those who are familiar with React apps, I am sure the first thing that comes to mind is state. If we tie the check/uncheck action with changing states, this will definitely have the desired effect.

Here, we are using the “foursomes” state to track the changes in content to be displayed on this page while the “applyHandicap” state is used to track checkbox value (checked or unchecked).

As for the checkbox itself, here is what I did in Semantic UI.

The “checked” attribute gets its value from the “applyHandicap” state so whatever value the state contains, it will be represented by the checkbox. The other important attribute here, of course, is the onClick event action. We will examine the “selectHandicap” function next to see how it works.

One important item to note is that whenever an action like a click occurs, our function gets two arguments — the event itself (e in the code above) and the attribute value caused by the action (a destructured “checked”). If I check the box on the page, “checked” will contain true and if I uncheck it, it will contain false.

Since the default behavior is to display all the foursome cards, I assigned whatever I have from the Redux store (this.props.foursomes) to the variable myHandiFour. No action will be taken if the box is unchecked. As a result, all the cards will be displayed as the “foursomes” state contains all the cards from the Redux store. However, if the box is checked, I applied a filter to the “foursomes” array in the Redux store and only return those foursomes with a handicap number within 3 of the user’s only handicap.

The lesson here is to set the state properly such that any subsequent action will be guaranteed the correct data to work with. As the Redux store gives us the complete set of foursomes, local state for the page component can be manipulated accordingly based on whatever action we desired. With the original data maintained within the Redux store, the complete set can easily be restored by refreshing from the store.

--

--

Used to manage software development in financial services. Recently acquired skills include full stack development and DNA extraction/sequencing.