Coding Journal

Jordan Vidrine

Daily Coding Journal

A Self-taught coder from the Cajun Prairie in rural Louisiana, currently working as a designer for Discourse.

I am always trying to better myself, and do so through learning new skills, trying out new routines, traveling, and pouring energy into hobbies. Since 2014, I have been recording, editing, and producing my own music under the name Skies Speak.

October 8th

After going through some exercises on spotting bugs in react, and fixing a non working Yahtzee game in order to function properly, we are moving on to the React Component Lifecycle.

We will be discussing what component lifecycle is; methods for mounting, updating, and unmounting; as well as less commonly used lifecycle methods.

Every component comes with methods that allow us to update application state and reflect the changes to the UI before/after key react “events”. Events as in the stages or lifecycles of the component (mounting, updating, unmounting).

Life Cycle Methods

When using a component, React first calls the components constructor(), it is often used for initializing state or binding event handlers to class instance. Next, the render() method is used. It tells React what should be displayed and React updates the DOM to match it’s output. The following from projects.wojtekmaj.pl/react-lifecycle-methods-diagram is a diagram of what the lifecycle.

ComponentDidMount()

componentDidMount() is a method lifecycle that we can use and React will run it for us after the component has mounted, after the first time it is rendered to the DOM.

It is a good place to load any data via AJAX or set up subscriptions/timers.

Example:

class Timer extends Component {
  constructor(props) {
    super(props)
    console.log("In Constructor")
  }

  componentDidMount(){
    console.log("In Component Did Mount")
  }

  render() {
    console.log("In Render")
    return <h1>TIMER</h1>
  }
}

// 1 -> In constructor
// 2 -> In Render
// 3 -> In Component Did Mount

componentDidMount() will only be called once. If the component re-renders, it will not be called again. Like previously stated, its best to call any timers you need or subscriptions you would need in this method. Lets look into this now.

Loading Data

For the following example we will use the Axios npm package to retrieve data from a simple API.

import axios from 'axios';

class ZenQuote extends Component {
  constructor(props) {
    super(props)
    this.state = {quote: ''}
  }
  componentDidMount() {
    axios.get("https://api.gitub/com/zen").then(response => {
      this.setState({quote: response.data})
    })
  }
  render() {
    return (
      <div>
        <h1>{`Always remember...${this.state.quote}`}</h1>
      </div>
    )
  }
}

Why can’t we do this in the constructor, instead of componentDidMount(). It is specified NOT TO by React, so, don’t do it.

Something to be aware of is that since the code inside of componentDidMount() wont be running until after the first render, there will be a visible delay between what is rendered, and what data is retrieved and stored.

Adding async in front of componentDidMount() will allow you to use javascript’s async/await functionality, not requiring .then or other methods we normally need to use outside of async functions.

Adding Animated Loaders

To do this, we can keep track of ‘loading’ in state. We can use conditional rendering to render either a loading animation or the data, based on the current state of the app. Pretty straightforward.

componentDidUpdate()

When state changes, props change, or an update is forced (forceUpdate()) we can use the componentDidUpdate() lifecycle method to run some code. It is called every time the DOM is rendered AFTER the first time it is rendered after componentDidMount() is run.

Accessing prevProps and prevState

Inside of this lifecycle method, we have access to the previous props and previous state in order to do a comparison between the previous and current state and props. To get this, we pass these like so in the method:

componentDidUpdate(prevProps, prevState) {
  // you can call setState here as well if needed
}

componentWillUnmount()

This is invoked immediately before a component is unmounted (removed from page). React Docs state that we can perform any necessary cleanup in this method, like canceling timers, network requests, or any subscriptions that were created in componentDidMount(). Calling setState() here is useless because there will be no re-rendering after this.

MongoDB

We will start off with an exercise to solidify some of yesterday’s learning about CRUD operations in the shell.

Inserting Records

use patientData
db.patientData.insertMany([
  {"firstName" : "Jordan", "lastName":"Vidrine", "age": 32, "history" : [{"illness":"cold"}]},
  {"firstName" : "Donald", "lastName":"Duck", "age": 64, "history" : [{"illness":"arrogance"}]},
  {"firstName" : "Hill", "lastName":"Billy", "age": 72, "history" : [{"illness":"amnesia"}]},
  ])

Updating Records / Inserting into an array of documents

We can use the $addToSet: operator to add information to an array of documents. This will add the document if it is not currently in the array.

db.patientData.updateOne({"firstName":"Jordan"},{$addToSet: {"history": {"disease":"tumor", "treatment":"surgery"}}})

Find info by query

The following would get all patients over the age of 45

db.patientData.find({"age":{$gt:45}})

Deleting by query

The following would delete all patients who have had a “cold” in their array of diseases and treatments.

db.deleteMany({"history.disease": "cold"})

Deleting a Database

This is really simple. Type in use [database name] then db.dropDatabase(). Be sure you really want to do this, as there is no turning back!

Algorithms and Problem Solving Patterns

In this section of the Algorithms course we will define what an algorithm is, devise a plan to solve algorithms, as well as compare and contrast problem solving patterns like frequency counters, two pointer problems, and divide and conquer.

This section will be more about devising a plan to solve a problem.

An algorithm is a process or set of steps to accomplish a certain task. Almost everything we do in programming involves some kind of algorithm. It is the foundation for being a successful problem solver and developer. What we will mainly be focusing on are algorithm problems that will come up in a coding interview.

How can we improve? - This doesn’t come naturally for a lot of people, but that doesnt mean we cant learn it!

  1. Devise a plan for problem solving.
  2. Master common problem solving patterns.

Problem Solving

  1. Understand the problem
  2. Explore concrete examples
  3. Break it down
  4. Solve/Simplify
  5. Look back and refactor

We will break down each step in the problem solving pattern to get better at problem solving. A lot of these strategies are adapted from George Polya’s How To Solve It.

Understand the problem

It can be tempting to want to start IMMEDIATELY. However, you will get further if you take a step back and make sure you understand the task ahead of you before you get too deep into the issue.

  1. Can I restate the problem in my own words?
  2. What are the inputs that go into the problem?
  3. What are the outputs that should come from the solution?
  4. Can the outputs be determined from the inputs? Do I have enough information to solve the problem? (This may not be answerable until you begin working on the problem, but its worht considering at the early stage.)
  5. How should I label the important pieces of data that are a part of this problem?

We will break down the following problem to demonstrate the above steps.

Write a function which takes two numbers and returns their sum

  1. “Make an adding function”
  2. ints? floats? larger numbers?
  3. same as above
  4. normally yes, but what if the user only inputs one number?
  5. with arument names? default arguments for if one number is passed in?

Exploring Concrete Examples

Coming up with examples can help understand the problem better.

write a function which takes in a string, and returns counts of each character in the string (do not include spaces, all characters should be converted to lowercase)

  1. Start with simple examples.
    • charCount('aaaa') // {a:4}
    • charCount('hello') // {h: 1, e: 1, l: 2, o: 1}
  2. Progress to more complex Examples
    • my phone number is 18273 ? should we store blank spaces?
    • Hello hi ? should we count lowercase and uppercase?
  3. Explore examples with empty inputs (edge cases)
    • charCount() // ??
  4. Explore examples with invalid inputs
    • charCount({7}) // what happens here??

Break It Down

Explicitly write out the steps you plan on taking. The basic components or steps of your solution. This will force you to think about the code you’ll write before you write it, and helps you catch any lingering conceptual issues or misunderstandings before you dive in and worry about details.

charCount(str) {
  // count the characters in str, storing the count of each character into a key value paid in an object. Once done, return that object to the user

  // charCount('Hi there')
  /* {
  h: 2,
  i: 1,
  t: 1,
  e: 2,
  r: 1
    }
  */

  // make object to return
  // loop over string
  // for each character that is number/letter, insert into object, or add to key value if it already exists
  // return object to user
}

Doing this would help you solve your problem and have a better layout of the issue before you begin. Interviewers also like to see your problem solving method. The instructor stated that he has seen students do this, but not be able to fully complete the exercise, and still get hired on, because the interviewer knew the candidate knew what they were doing.

It’s all about the process and how you think about problems, not JUST your ability to solve them.

Solve the problem

If you cant immediately solve the issue after the previous steps it’s possible to try and solve a smaller component of the larger issue at hand. It can often look bad if you try and put all of your eggs in one basket and try to solve the entire thing even when you don’t know the solution.

This is why it’s much better to begin to solve where you currently know where to start.

Back to blog...