DEV Community

Cover image for The Rising Coder - Week 9/13 (Frontend Week 2/3)
Christopher Lam
Christopher Lam

Posted on • Edited on

The Rising Coder - Week 9/13 (Frontend Week 2/3)

Good morning, good afternoon or good evening and thank you for once again coming back to check on in The Rising Coder blog, I really do appreciate it!

Last week may have been perhaps an over reaction (puns intended) as this week after a coming back with a fresh perspective and mind, we dove more into solidifying our knowledge of React Hooks and State management!

But before I dive straight into what I have been up to this week on the Northcoders Bootcamp - I would like to say a huge thank you to Christian Dutton and Mitchell Wyatt who were respectively our seminar lead and mentors for Seminar Group 1!

For Christian, it is his first time leading a seminar group and he has been the most supportive and personable person for the job and he has done amazing work! Similarly, Mitch who had joined during the Backend portion of the course has done a brilliant job fitting right in and always keeping us all in good spirits whenever we were down.

I wish the best for the both of you in your next cohort group that you will be mentoring, and I'm sure you will both do absolutely smashingly!

Last week over-reaction? How did I React this week?

In order to summarise this week, I would say that I reacted pretty positively to the content that was covered. Perhaps I was over-reacting last week due to fatigue, who will ever know!

However, needless to say that this week I believe that I've soaked up all of the information that was taught like a sponge, and so before I proceed with details pertaining to what we had learned this week, feel free to check out a few of the projects I had worked on this week:

Topics Covered

  • Fundamentals of the React Hook: useEffect and the dependency array
  • Fetching Data in React with native Fetch & Axios
  • React's Loading Pattern
  • Introduction to React Router - Links & Routes
  • Introduction to the concept of Optimistic Rendering

React Hook: useEffect()

The first topic that we learned this week was a new React Hook called the useEffect hook. This hook allows us to render a piece of information a finite amount of times depending on the "dependency array" that is inside the useEffect call.

The useEffect hook takes in two arguments:
1) The effect that it will want to run
2) The dependency array - An array of variables that the useEffect will depend on.

With this hook, it will only run the function passed in when it detects a change within the variables in the dependency array. If it is not passed in any variables to detect for change, then it will only run a single time.

Let's say that you load up a new "Account" page that depends entirely on the "username" value to fetch the data pertaining to that specific user. IN this case, you would want to run the useEffect hook to fetch that data everytime the "username" changes.

An example of this is in my previous "Northcoders-Marketplace" project that is listed above, where I have a list of users that the user could login to and change the "Username" state.

As the dependency array is looking for any changes in the "username" state, it will run the useEffect again to fetch information for that user:

 useEffect(() => {
        setIsLoading(true);
        API.fetchAllItems()
        .then((itemsData) => {
            setItems(itemsData);
            setIsLoading(false);
        });
    }, [username])
Enter fullscreen mode Exit fullscreen mode

The useEffect hook is a significantly powerful tool in the right hands, but remember to always think about the context of which you are using this hook. During the near-end part of building up the Marketplace project, the useEffect's dependency array had caused me a few headaches because I didn't take into account that the useEffect would run anytime any of the variables changed!

Fetching Data with Fetch & Axios

For the first two-days that myself and my partner were building up the Pokédex Stat Checker - we were exposed to two different methods of fetching data.

The first of which was the native Fetch method that is available on all browsers. This method simply revolves around passing in a valid API endpoint to fetch information from. Once the data has been fetched as an unresolved promise, you would need to parse it through as a JSON object, and then get access to the information.

An example of the native Fetch method would look something like this:

useEffect(() => {
        setIsLoading(true);
        if(userInput.length > 1) {
            fetch(`https://pokeapi.co/api/v2/pokemon/${userInput}/`)
            .then((response) => response.json())
            .then(({id, name, sprites:{other}, species, stats}) => {
                setIsLoading(false);
                const returnedPokemon = {
                    id, 
                    name,
                    other,
                    species,
                    stats
                }
                return setRequestedPokemon(returnedPokemon)
            })
        }
    }, [setIsLoading, userInput, setRequestedPokemon])
Enter fullscreen mode Exit fullscreen mode

Although visibly there's a lot going on - simply what this is doing is making a new Fetch call to the PokéAPI everytime that the value of setIsLoading, userInput and setRequestedPokemon state functions are changed.

Once the data has been successfully fetched from the API, it is then going to set the requestedPokemon state with the returned Pokemon variable.

The second method of the Axios library makes our lives a bit easier because it provides us the information without having to use Response.JSON() to convert it into a JSON object for us to use, and also provides us more information on the Error Codes that we will need in order to handle any errors that come back from the database.

Axios requires a bit more setup but here is an example taken from my codebase:

import axios from 'axios;

const marketplaceApi = axios.create({
  baseURL: "https:/marketplaceapi.herokuapp.com/api/"
})

export const fetchAllItems = () => {
  return marketplaceApi.get('/items');
  .then((response) => {
    return respone.data
  })
 }
Enter fullscreen mode Exit fullscreen mode

As Axios is a package we would need to run npm install axios and then following standard ES6 syntax, import the package where we would need to use it.

The first thing we do after importing is create a "baseURL" variable by first declaring a variable called marketplaceApi and using the axios.create() method, which just involves creating an object with the baseURL property key and the API of choice's link as the value.

The next thing to do is create functions that returns the marketApi with a HTTP method such as GET. Once it has resolved as it is a promise, we get access to the data on a key of data - in which afterwards we are able to use the information as we choose!

React and the isLoading pattern

You may have seen in the previous code snippets on this blog where we've set state for a state called setIsLoading() - so, what does this actually mean and why do we do it?

The isLoading pattern in react is a way for us to display to users a "Loading" screen whilst the data that is being requested by the user is being fetched from an external API.

 useEffect(() => {
        setIsLoading(true);
        API.fetchAllItems()
        .then((itemsData) => {
            setItems(itemsData);
            setIsLoading(false);
        });
    }, [username])

  isLoading ? 
    <h1> Currently Loading Items </h1> :
    <ul className="items-list">
      {items.map(({ item_id, item_name, description }) => {
        return <li key={item_id} <p>{item_name} {description}</p> </li>
      })
    </ul>
Enter fullscreen mode Exit fullscreen mode

This exact same code snippet from earlier is a useEffect that only re-renders whenever the username state changes in the application. When it does, it will the the isLoading state variable to true, in which case it would a basic loading screen.

Once it has finished loading up the data that was being fetched from the external API, it will then set the loading state variable to false and then display the information that was fetched.

React Router - BrowserRouter, Routes, Route, Link

As React is a SPA (Single Page Application), it means that instead of hard reloading the website like traditional websites do, we instead focus on re-rendering components based on state changes.

This does not mean however that we are unable to create different routes that visually display to users in the address bar that we're in another "section" of the website.

For example, even without context you can most likely infer that the following link is a page related to resetting your password: https://fakesite.co.uk/account/forgotten-password

With the use of an external library called React Router DOM, we are able to mimic a traditional website and provide meaningful URL endpoints to ensure that users aren't confused about which section of the React website they are on.

React Router Setup

import { BrowserRouter, Routes, Route } from 'react-router-dom';

const App = () => {
  return (
    <BrowserRouter>
      <div className="App">
        <h1>My App </h1>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/topics" element={<Topics />} />
          <Route path="/about" element={<About />} />
        </Routes>
      </div>
    </BrowserRouter>
  );
};

// src/components/Home
const Home = () => (
  <div>
    <h2>Home</h2>
  </div>
);
Enter fullscreen mode Exit fullscreen mode

In order to do this, we will need to import BrowserRouter, Routes, Route, and Link from the react-router-dom library after downloading it.

After that, we wrap the entire "App" in App.js with the BrowserRouter function so that it will have global access to the React Router's methods.

The next part is to decide which elements on your page if clicked will go to which path. For example here, the Home component if pressed will take the user to the root path of /, whilst conversely if the user clicks on the Topics or About component then they will be respectively sent to those paths.

React Router's Links

If you have learnt a bit about HTML and the <a> anchor tag that is home to a button that if pressed will redirect the user to another location.

This is React Router's way of essentially redirecting the user to a certain part of the website if they click on a link.

For example:

<nav>
  <Link to="/"> Home </Link>
  <Link to="/services"> Services </Link>
  <Link to="/about"> About </Link>
</nav>
Enter fullscreen mode Exit fullscreen mode

Here if the user clicks on any of these links then they will be redirected to the relevant endpoint that is specified after the "Link to".

Introduction to Optimistic Rendering

The final lecture of the week was on a concept that is called "Optimistic Rendering". This concept is essentually thinking mostly about the user experience. Optimistic Rendering by definition is rendering UI changes without confirmation of success from the backend based on the assumption that the request will succeed.

An example of this would be having Reddit's Upvote & Downvote buttons. With optimistic rendering, we are able to render a UI change of the votes on a comment being up/downvoted without confirmation from the server. This is because if we think about it from the user's perspective, an upvote/downvote is not an important feature that will impact them, but because there's no optimistic rendering, they would have to wait a couple of miliseconds/seconds to have confirmation that their upvote/downvote went through.

However, this does not mean that we would want to always optimistically render. When we want to consider the possibility of an optimistic render, we need to ask ourselves how important is it that the user receives confirmation on an action they do on the website.

For example, if you wrote a hurtful comment on Reddit and want to delete it from Reddit, you wouldn't want to optimistically render and automatically assume that the message was deleted. Because chances are that if you receivee an instant feedback that it was deleted but in reality an error occurred on the server side, then that comment you thought you had deleted remains there.

Or perhaps you're shopping on Amazon and because of optimistic rendering, the website says that the transaction was succesful and has pulled money from your bank account - even though there was a server-side error processing the transaction.

As you can see the context of deciding when we would optimistically render changes without confirmation are heavily dependent on the context!

Thoughts Going Forward

With that final short introduction to optimistic rendering, this brings us to the end of yet another blog post and here comes the final frontend project phase! It's been a rollercoaster from the beginning of the Front End section but I believe that my confidence and overall likeability towards the Front End side of development has started to pop its head out.

Mostly because going from the Backend portion of the course where we had a lot of structure in terms of our learning to being left to our own devices. However, the section of the course where we were encouraged to plan everything from start-to-finish and create a template for ourselves to work with helped me regain the once lost structure and it became a lot more enjoyable from there!

With that, thank you as always for reading to the very end and I hope that you all have hopefully learned something new or strengthened some topics that you may have been weak on prior to reading this, and I will see you again after the final Front End project phase!

Socials

Feel free to give me a follow on any of my socials down below!

Top comments (0)