DEV Community

Cover image for Keeping tabs on Bitcoin
Luc van Kerkvoort
Luc van Kerkvoort

Posted on • Edited on

Keeping tabs on Bitcoin

Hi everyone,

I have been wanting to create a repository with Front end Interview questions for quite some time now.
I wanted to share my knowledge and the kind of coding exercises you can expect when going for a front end role.

To keep everything comprised I decided to make this into a series talking about a single coding exercise in each one to keep it concise and easy to lookup.

TLDR

I have made a repository with React and HTML, CSS and Javascript solutions to coding exercises from Front End interviews.
Github link

Bitcoin

I got the following question:

Given an API that returns the latest price of Bitcoin.
Create an application that has a button saying Get Bitcoin.
The color of the button at the start should be blue.
After it is clicked it should change color to purple and the text should change to refresh Bitcoin price.

Showcase the current price as returned from the API. After clicking again it should also showcase the previous price.

If you want to you can use the URL in the Github repo to code out your own solution. Otherwise you can keep reading and follow along to my approach

Approach

Let's think about the necessities to make this operation work. Here is a list of elements needed.

  • API call
  • A button that can change colors
  • A data structure to hold the current and previous value.
  • Two paragraphs to store the values in

React Implementation

API Call

When it comes to React I enjoy using the hooks approach. The API call and the setting of values can be combined into a hook that will just return the value, and the function to make the API call.

import { useState } from "react";

export const GetBitcoin = () => {
  const [bitcoinPrice, setBitcoinPrice] = useState([]);

  const getCoin = async () => {
    try {
      const call = await fetch(
        "https://api.coinbase.com/v2/prices/BTC-USD/buy",
        {
          method: "GET",
          authorization:
            "Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c",
        }
      );
      const response = await call.json();
      storeAmount(response);
    } catch {
      return [];
    }
  };

  const storeAmount = ({ data }) => {
    if (!data) return;

    const { amount } = data;

    const prices = [parseInt(amount), ...bitcoinPrice].slice(0, 2);

    setBitcoinPrice(prices);
  };

  return { getCoin, bitcoinPrice };
};

export default GetBitcoin;

Enter fullscreen mode Exit fullscreen mode

I have encapsulated the API call, the function is exposed so the call can be made, but the logic for storing the amount is not being exported or available.

My choice for using hooks is that we have a clear seperation of concerns when it comes to UI and Logic. I can make quick changes to logic and the logic has become modular, if I wanted to implement the same logic on a different part of the application I can just use the hook.

UI

for the UI we have to take into consideration the following

  • A button to make the API Call
  • A paragraph to show the previous and current price
  • A way to showcase that the button has been pressed

for my implementation I used styled-components a library that allows the CSS to use JavaScript to check for properties of the element.

import React, { useState } from "react";
import GetBitcoin from "./api";
import { Button, List, Application } from "./styles";

function App() {
  const [hasBeenPressed, setPressed] = useState(false);

  const { getCoin, bitcoinPrice } = GetBitcoin();

  return (
    <Application className="App">
      <Button
        isPressed={hasBeenPressed}
        onClick={async () => {
          if (!hasBeenPressed) setPressed(true);
          getCoin();
        }}
      >
        {hasBeenPressed ? "refresh Bitcoin price" : "get Bitcoin price"}
      </Button>
      <div>
        {bitcoinPrice && (
          <List>
            {bitcoinPrice.map((value, i) => (
              <div key={i}>
                {i === 0 ? "Current price: " : "Previous price: "} {value}
              </div>
            ))}
          </List>
        )}
      </div>
    </Application>
  );
}

export default App;

Enter fullscreen mode Exit fullscreen mode

as you can see the only state within the application itself is the hasBeenPressed state. Keeping track on whether the button has been pressed.

for the logic I use ternary operators to decide what to showcase. The other logic is coming from the Hook we implemented before.

Styling

Like I mentioned before I used styled-components to create the different UI elements. Styled components create React elements that can take in properties to set styling.

import styled from "styled-components";

export const Button = styled.button`
  background-color: ${({ isPressed }) => (isPressed ? "blue" : "purple")};
`;

export const List = styled.div`
  display: flex;
  flex-direction: column;
`;

export const Application = styled.div`
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
`;

Enter fullscreen mode Exit fullscreen mode

As you can see I'm setting the background-color on the Button to blue or purple depending on the property isPressed, which has a boolean value

JavaScript Implementation

For the JavaScript implementation I went a little more rudimentary. I decided to go with an approach where it all fits into a single document, most of the time when you get coding exercises and bigger firms they only allow a single HTML file, using a script tag to separate the JavaScript from the HTML and inline styles.

Javascript

I've created the following functions:

  • FetchBitcoin
  • SetData
  • Change Color

FetchBitcoin

This is the API call that gets triggered whenever the user clicks on the button. This is the major function being called and basically calls the other functions inside of it.

For this purpose I think it is fine since we are not thinking about reusable modular code here. If that was the case we could use encapsulation to make the code more modular.

SetData

This is the most intricate of the functions in this file. I've given some thought as to what data structure I want to use here. I decided to go with a Queue approach since we will have two values to keep track off and new ones keep getting added to the front (current value) and old ones are popped off from the back (previous value) so we have a moving Queue.

changeColor

this function changes the background color from the initial blue to purple. I added an if statement so the change only happens ones and not on every API call.

<script>
      const availableData = [];

      const setData = (data) => {
        if (availableData.length > 2) {
// remove the previous value from the array
          availableData.pop();
        }

// add new value to the start of the array
        availableData.unshift(data);

        const [currentData, previousData] = availableData;

        document.getElementById(
          "current"
        ).innerHTML = `Current Price: ${currentData}`;

        if (previousData) {
          document.getElementById(
            "previous"
          ).innerHTML = `Previous Price: ${previousData}`;
        }
      };

      const changeColor = () => {
        const button = document.querySelector("button");

        if (button.style.backgroundColor === "purple") return;

        button.style.backgroundColor = "purple";
      };

      const fetchBitcoin = () => {
        changeColor();
        const response = fetch(
          "https://api.coinbase.com/v2/prices/BTC-USD/buy",
          {
            method: "GET",
            authorization:
              "Bearer abd90df5f27a7b170cd775abf89d632b350b7c1c9d53e08b340cd9832ce52c2c",
          }
        )
          .then((response) => response.json())
          .then(({ data: { amount } }) => setData(amount));
      };
    </script>
Enter fullscreen mode Exit fullscreen mode

HTML

I used VSCode code snippets to fill out the boiler plate code for HTML5. I have created only 3 elements for this exercise:

  • button
  • paragraph for current price
  • paragraph for previous price

I decided to go with inline styling to set the color for the button on page load. This way I wouldn't have to add a CSS stylesheet for just a single button color change.

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Bitcoin</title>
  </head>
  <body>
    <button style="background-color: blue" onclick="fetchBitcoin()">
      Grab Bitcoin
    </button>
    <p id="current"></p>
    <p id="previous"></p>
  </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Thank You

I hope this helps any of you out there that are in the process of interviewing for Front End positions.

I would appreciate any feedback or any comments you have on my code and I encourage you to post your own solutions in the comment sections as well. If we all help each other we can all become better developers.

I will be posting part 2 tomorrow.

Top comments (0)