B

Backend developer learning Frontend – Part 1

Remote & Travel

I have been a software developer for about 6 years, most of them spent coding in Java. During university years I tried out several languages, different coding approaches and I remember that every time I kept floating towards backend development. Not only because my creativity in design is almost non-existent or that I don’t like coding the visual side of an application, but because I like more playing with algorithms and the logical part of an app.

So, I started with an internship in PHP which I loved and where I learnt more about how the backend world really works. I remember thinking ‘Yes! I picked the right path for me!’. But only after my first job coding in Java I realised that JVM is something that I want to continue doing.

After a number of Java projects, a couple in Scala and a few scripting here and there, I tried out some frontend projects. Not too big, mostly theme work, all concerning only the visual part and working only with HTML, CSS, Bootstrap and jQuery. I liked it, but it wasn’t something that motivated me that much.

Backend is still my cup of tea and I would not be giving it up too soon. Only that now I start seeing a perspective where a developer should not focus only on one language or one coding approach. An experienced developer should be able to code in whatever comes on their plate, or maybe at least know the concepts behind it. Victor also talked about this in his article.

Frontend looks a lot different than what it used to look 5 years ago. Nowadays, existing frameworks for the client side can be used to implement the entire web application, including the backend logic. Frontend doesn’t represent today only the stylisations or the animations for the visual part, but also coding the behaviour of the app or the interactions between its layers.

New challenge

The challenge that I want to take in the next period of time and that I want to document in a series of blog post is to learn frontend development to a level where I could take on a complex project at any time. The way that I want to do this by taking an idea and transforming it into a proper web application, hoping  that by the end of implementation I would have gained the knowledge that I want.

Victor is already a frontend developer and could help me with this at any time, but my goal is to do this by myself, the way a self-taught developer would do it. I will try to document every step on the way, all the challenges, problems and of course, the solutions that I found to them.

The idea

What I intend to build is two web applications, one for backend and one for frontend, managing a set of entities in the backend, while the frontend will manage user interactions and do requests to the APIs. As a backend developer, this is all the information I have about how I want to start this:

Backend:

  • a set of REST APIs with CRUD operations over the entities managed by the application: Countries with their respective information, Cities with their respective information, City Highlights to visit with descriptions and also images that will be showed in the UI
  • the APIs will be implemented in Java with Spring Boot (I can not be more thrilled about what Spring has done with Spring Boot, but about this maybe in another post)
  • will use MySql as a database for the sake of simplicity and not to overthink the app (after all, the focus is on frontend)

Frontend:

  • pff, no idea yet!
  • I should go with one of those popular JavaScript frameworks that exist, like AngularJs, VueJs or ReactJs

Having all this in mind, the first step that I took was implementing the backend, which I am not going to focus on now. No challenges there, only CRUD operations with very little configuration. After all, Spring Boot is kind of like magic!

Starting the implementation for Frontend – ReactJs

Because I did not know exactly which framework to choose, I researched a little bit about every one of the three mentioned above. All of them are great choices for implementing single page applications, all of them also focusing on reactive implementations.

Analysing the three, I formed some opinions. While I seemed to wrap my mind around AngularJs easier having a backend thinking kind of way, it is more verbose to code in than the other ones. VueJs is not that verbose, quite easy to understand, kept it in my mind as a the probable option. That is until I learnt about ReactJs. Maybe because it is different than the other two, maybe because it seemed like a bigger challenge to learn it, but it resonated with me more.

So ReactJs was the choice of framework I made for my application. After a few videos I watched regarding the topic and not managing to understand fully all the concepts of this framework, I stumbled upon this one. I can honestly say I had ‘Aha!’ moments across almost the entire video. So, I would advise watching it if you are at the beginning of the road with ReactJs also. Huge help 🙂

First impression about ReactJs:

  • After working only with jQuery in JavaScript and the way I used to implement the logic with it, I liked the way how React helps you write less code for your complex scenarios in your application
  • Even though I noticed among developers they don’t really like returning directly HTML in Javascript code, I actually like it. As a backend developer, somehow this makes sense to me and if it helps writing logic faster, why not.
  • I like that is component oriented, but then again, almost all frameworks alike are
  • I am also liking that besides the components, the framework focuses on writing Javascript code including the HTML and not focusing on templates. Maybe this is also because the backend developer in me or just a preference.
  • Every component has a state. Cool, so I can compare them easily with the classes I have on backend.
  • Lifecycle hooks on the components seem like they are going to help a lot in the process
  • It seems like it is easy to add 3rd party integrations with ReactJs, like Bootstrapm that should also help with the visual side

So I started implementing the application. Easy-breezy to start with, using their boilerplate with:create-react-app. They already created a ‘hello world’ component for you, so no challenges there.   The first thing that seemed to makes sense to do was some requests to an entity from my already implemented API and then see what I can do from there.

Choosing the Country entity, the first challenge was to show on the home screen a list with all the Country codes with a button near them and when that button is clicked to show below the information about the selected country. For the purpose of making things looks a little nicer from the beginning I added reactstrap to the app. The code that I ended up with is:

class App extends Component {
  constructor() {
    super();
    this.state = {
      countries: null,
      selectedCountry : null
    }
  }
  componentDidMount() {
    const URL = "http://localhost:8080/countries";
    fetch(URL).then(res => res.json()).then(json =>
      this.setState({countries: json})
    )
  }
  getCountryInfo(event) {
    const URL = "http://localhost:8080/countries/" + event.target.getAttribute('data-country');
    fetch(URL).then(res => res.json()).then(json =>
        this.setState({selectedCountry: json})
    )
  }
  render() {
    const countries = this.state.countries;
    const selectedCountry = this.state.selectedCountry;
    return (
        <div className="App">
            <header className="App-header">
              {!countries && <Alert color="info">
                                  Loading...
                              </Alert>
              }
              {countries &&
                  <ul>
                    {
                      countries.map((country, index) => {
                        return (
                            <li key={index}>
                              <div className="name pull-left">{country}</div>
                              <Button className="btn btn-primary pull-left" data-country={country} onClick={this.getCountryInfo.bind(this)}>Get Info</Button>
                            </li>
                        );
                      })
                    }
                  </ul>
              }
              {selectedCountry &&
                <section className="countryInfo">
                  <div className="code">{selectedCountry.code}</div>
                  <div className="name">{selectedCountry.name}</div>
                  <div className="currency">{selectedCountry.name}</div>
                </section>
              }
            </header>
        </div>
    );
  }
}

All I can say is what you see is not how I wrote the code the first time. While the above piece of code does exactly the job, what I wrote the first time was not even close. So let’s see the challenges that I had and what needed to change in how I think as a frontend developer:

  • Noticed from the start that class attribute for HTML elements are not marked with the word  class  but with  className . This seems to be because class is reserved for declaring the actual classes
  • I wanted to request all the country codes at load time, but did not know exactly how. It popped up into my mind there were some hooks for the components in React so it seems componentDidMount  did the trick
  • I tried to use an  if conditional to show to the user either that the component is loading or the list of countries. Somehow, the code did not compile with the  if  so I came up with the conditionals above. Sure, the  if  would have worked outside of the return, but I wanted to have all the code into the same block, at least for now.
  • A challenge was to give the country code value to the button for it to know how to make the next request. First I wrote it like   onClick={this.getCountryInfo(country)} . A pretty bad idea, given the fact that would mean calling the method immediately, ending in an error. So the action needed to get only the reference of the method, thus the code became  onClick={this.getCountryInfo}  and assigning the country code to a parameter in the target
  • So at first, the  onClick  action from the button did not have a bind to  this . Because of this, I got an error every time I clicked the button, because the context of  this  from  this.setState  was the button context and not the class context. Lesson learnt!

Adding Redux

Cool! I managed to implement code so far and also encountered some challenges, thus learning something new. At this point I wanted to see some best practices, so reading a few articles I kept stumbling upon Redux. I remembered Victor and some friends talking about it, I knew what it helps with, but I never managed to put my hands on it and implement something.

I also found out that Redux and React work hand in hand, so it seemed to be something I should add on. So I started. Reading the documentation, watching a few videos and trying to understand as best as I could how it works.

Oh boy! You have reducers, you have the actions, mapping state to props or actions to props, all mixed up and somehow working together. I remember being frustrated I was not able to understand very well the concept and why exactly is it that helpful. So,  npm install redux  and let’s see if writing code may actually help me be more enlightened.

So far I know every change in the UI should dispatch an action -> the actions return a payload -> that payload is used by a reducer to update a value from the state -> every component that uses that value from the state will be re-rendered.

In my case I should have 2 types of actions and 2 types of reducers: one for loading all the country codes and one for getting information about a selected country. Piece of cake! Or not! At least, not for the backend developer in me. As a reference, I used this article to help me implement what I want.

I ended up with the code below.

The types used by both actions and reducers:

export const SUCCESS_COUNTRIES = 'SUCCESS_COUNTRIES';
export const SUCCESS_SELECTED_COUNTRY = 'SUCCESS_SELECTED_COUNTRY';

The actions dispatched to update the state of the app:

export const updateCountries = (countries) => ({
    type: SUCCESS_COUNTRIES,
    payload: countries
});

export const updateCountryInfo = (countryInfo) => ({
    type: SUCCESS_SELECTED_COUNTRY,
    payload: countryInfo
});

The reducers that actually update the state:

const defaultState = {
    countries: null,
    selectedCountry: null
};

const countryReducer = (state = defaultState, action) => {
    switch (action.type) {
        case SUCCESS_COUNTRIES:
            return { ...state, countries: action.payload };
        case SUCCESS_SELECTED_COUNTRY:
            return { ...state, selectedCountry: action.payload};
        default:
            return state;
    }
};


export default combineReducers({countryReducer});

The store itself:

const store = createStore(
    reducers,
    applyMiddleware(logger)
);

And the initialisation of the App in index.js that now must provide the store, in order for the state to be available across the entire context:

ReactDOM.render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
);

Finally, the App class looks like this:

class App extends Component {
  componentDidMount() {
    fetch("http://localhost:8080/countries")
      .then(res => res.json())
      .then(res => dispatch(this.props.updateCountries(res)));
  }
  getCountryInfo(event) {
    const URL = "http://localhost:8080/countries/" +
        event.target.getAttribute("data-country");
    fetch(URL)
      .then(res => res.json())
      .then(res => dispatch(this.props.updateCountryInfo(res)));
  }

  render() {
    const countries = this.props.countries;
    const selectedCountry = this.props.selectedCountry;
    return (
      <div className="App">
        <header className="App-header">
          {!countries && <Alert color="info">Loading...</Alert>}
          {countries && (
            <ul>
              {countries.map((country, index) => {
                return (
                  <li key={index}>
                    <div className="name pull-left">{country}</div>
                    <Button
                      className="btn btn-primary pull-left"
                      data-country={country}
                      onClick={this.getCountryInfo.bind(this)}
                    >
                      Get Info
                    </Button>
                  </li>
                );
              })}
            </ul>
          )}
          {selectedCountry && (
            <section className="countryInfo">
              <div className="code">{selectedCountry.code}</div>
              <div className="name">{selectedCountry.name}</div>
              <div className="currency">{selectedCountry.name}</div>
            </section>
          )}
        </header>
      </div>
    );
  }
}

const mapStateToProps = state => {
  const { countries, selectedCountry } = state.countryReducer;
  return {
    countries,
    selectedCountry
  };
};

const mapDispatchToProps = { updateCountries, updateCountryInfo };

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(App);

Oh my, oh my! I felt that for a short example with a simple scenario, it took me a while to get around how it works. A way to implement certainly different than what I am used to when writing server code. My impressions after playing with Redux?

  • If at the beginning I didn’t understand why do I have to write so much code for just having a common state across the entire application, now I feel that for more complex logic it actually helps writing less code.
  • I had some difficulties in understanding all the ‘configuration’ code, like mapping the state or actions to props, combining the reducers or initialising the store. Not too much, but I had to change the way I was thinking for a bit.
  • After coding an example or two, Redux grows on you. It starts to make sense and not using it seems like a hustle.

Where I got with the example above can be found here.

Going further

Now that I felt I had somehow an understanding of how frontend development works, Victor asks me just out of curiosity if I started the implementation using TypeScript. Wait what?! I have not thought about it. Rookie mistake! I knew about Typescript and knew about the advantages of it, but it totally slipped my mind.

So now I am on the search again on maybe finding a boilerplate on GitHub that contains the trifecta: ReactJs + Redux + TypeScript. Tried a few, but nothing really stuck as it seems that a good starting kit using the three is a little more complex. Not too long into my research, I found something that seemed promising and which was more than a boilerplate: JHipster.

First words about JHipster? Magic! It helps you built a web application with whatever integration you may need, including the starting backend. Nonetheless, I started to look into it and so far I am really impressed.

But more about JHipster and nonetheless about learning frontend and its challenges maybe in a future post.

Until then, I am curious about other backend developers learning frontend and their journey, so raise your hands! Let’s discuss!

To be continued.

CategoriesCoding

Leave a Reply

Your email address will not be published. Required fields are marked *

Remote & Travel