Creating Functions

Learn to create functions in an application with Redux.

To make our demo functional, let’s create a click handler for each button that will use the dispatch() function to notify our store that an action needs to be performed:

dispatch(action);
//Connecting click events to dispatch()

// Listen to click events
document.querySelector('#inc').onclick = () => dispatch('INC');
document.querySelector('#dec').onclick = () => dispatch('DEC');

We will come back to its implementation later. Also, let’s define a function that will update the counter's value in the HTML based on the application state received as an argument:

//Code to update the counter in the DOM 

// Function to update view (this might be React or Angular in a real app)
function updateView() {
  document.querySelector('#counter').innerText = state.counter;
}

Since we want our view to represent the current application state, we need consistent and reliable updates every time the state (and the counter) changes.

We will use the subscribe() function, which we will also implement a bit later. The role of the function will be to call our callback every time anything in the state changes:

subscribe(updateView);

Our Application looks like this:

Get hands-on with 1400+ tech skills courses.