Front-end

React Hooks

There are many hooks out there but master three and you'll be fine.

useState

...

const Toggle = () => {
    const [show, setShow] = useState(false)
    return (
        <div>
            <p>{show ? "Hello there!" : "..."}</p>
            <button onClick={() => setShow(!show)}>
            Show me
            </button>
        </div>
    )
}

useState initialises a pair of variables - one is a state and the other is a function to change it. In this case, show is the state that is initially set to false. The setShow variable is put into the button so that whenever it's clicked, show will be toggle from true to false, vice versa.

The function in the p tag is an if else statement that shows "Hello there!" if true and "..." if false.

useEffect

7:17:52 AM

const Time = () => {
    const [time, setTime] = useState(new Date());

    useEffect(() => {
        const timer = setTimeout(setTime(new Date()), 1000)
        return () => clearTimeout(timer);
    })

    return (
        <div>
            <p>{time.toLocaleTimeString()}</p>
        </div>)
}

useEffect fires a function only after the DOM is rendered. This basically means that everything on the page will load first before useEffect does additional work. This clock doesn't badly justify the use of useEffect, but it'll do as a demo.

It is possible to render the time without useEffect, but you'll only get the time at the time the page was rendered. The seconds of the clock won't move until you refresh the page.

useEffect allows setTime (from useState) to get reinitiate the new Date() function every 1000ms or 1 sec so that the time gets updated

useContext

Grandparent

Parent

Child

.... I got candy!!!

Above is the demo. The string "I got candy" is being passed from Grandparent to Parent to Child. Refer to the code in ../demo/useContext.js'.

useContext is the Hooks version of React's Context API. It initialises a pair of attributes called Provider and Consumer.

In Context Api, the highest parent components that pass the data is wrapped with .Provider.

  <GiftWrapper.Provider value={candy}>
    <p>Grandparent</p>
    <Child />
  </GiftWrapper.Provider>
Grandparent component

Child components receiving the data is wrapped with .Consumer.

  <GiftWrapper.Consumer>
    <p>Child</p>
    <p>{value=>value}</p>
  </GiftWrapper.Consumer>
Child component

At the child level, all useContext does is replace it with simpler to read code.

const Child = () => {
    const value = useContext(GiftWrapper);

    return (
        <div>
          <h4>Child</h4>
          <p>{value}</p>
        </div>)
    }
Child component with useContext

Gatsby

Using .mdx files to build your pages can be extremely convenient. MDX can take in React, html and markdown formats.

Install

npm install gatsby-plugin-mdx @mdx-js/mdx @mdx-js/react

Configure gatsby-mdx in the gatsby-config.js file:

plugins:[
    {
      resolve: 'gatsby-plugin-mdx',
      options: {
        defaultLayouts: {
          default:require.resolve(
            './src/components/layout.js'
            )
        }
      }
    }
    ]

There's no need to wrap the .mdx file in your <Layout/> component. This will automatically be done because the path is already pointed to layout.js.


MySQL

MySQL + React + Node is possible. The concept is this - MySQL sits in the backend with the data which Node fetches for the React frontend to display.

In this case, the root project directory holds two things - server.js and the React app. You need to readjust a little if you've been used to having create-react-app as the root.

There's a bit of thinking to be done to put all three pieces together.

Tutorial to Read the database with Node. This will get you only as far as MySQL + Node. And then in the directory, create-react-app.

Tutorial to fetch from the database's localhost. This tutorial fetches from its another api. Replace the url inside fetch() with you database's url (localhost:5000 for example). An error is expected.

Tutorial to solve CORS error. Because React's localhost:3000 is fetching from the database's localhost:5000, you'll run into a CORS error. It's basically a security feature that prevents localhost fetching from localhost.

Tutorial to CRUD. CRUD is Create, Read, Update, Delete from the database. You already have R in the first tutorial.

It's not a straight forward guide, but it'll get you there.

CRUD

Before jumping into CRUD, one needs to understand the client-server connection and everything in between. Take Facebook for example. It's an app where you can read, create, edit and delete posts. That's CRUD. When you enter a URL (https://www.facebook.com/matthew), your computer - the client - is searching for a specific address in facebook's server. This guy was probably the first ever Matthew on Facebook. Let's pause here to breakdown the parts of a URL.

  • Transfer protocol: In this case, the transfer protocol is the TCP (Transmission Control Protocol). The protocol its using is the HTTP. Contrary to what I assumed before, the HTTP is not the same thing as the URL. It's the transfer protocol for which Read from CRUD happens.
  • Domain name: Facebook's domain name is facebook.com, it's unique address. You could buy a johndoe.com as your own domain name.
  • Path: more '/' mean more folders in that server.
  • File name: The main file which servers up your webpage. You'd have your own file in facebook's server named after your id.

So how do you CRUD? The answer lies in Respresentational State Transfer (REST) architecture that uses HTTP to CRUD. There are 4 HTTP Requests that can but don't always correspond to CRUD.

HTTPCRUD
POSTCreate
GETRead
PUTUpdate
DELETEDelete
POST http://www.social-media.com/someGoTfan/post-id-105

I feel like talking about Game of Thrones today. Let me share it out there. I wrote about how John Snow's a Stark and posted it online.

GET http://www.social-media.com/someGoTfan/post-id-105

It says, "John's the bastard son of Ned Stark. So he's technically half Stark."

PUT http://www.social-media.com/someGoTfan/post-id-105

No, no. Turns out he's a Targaryen. "John Snow's house dragon."

DELETE http://www.social-media.com/someGoTfan/post-id-105

The ending sucks. I'm gonna delete this post.

~ Post deleted! ~

So when are the times when they don't correspond to CRUD? When you use a POST or GET to do all CRUD. Some times, all you need to do is send an SQL query to the database. The queries will dictate the terms with which CRUD methods are called. In these cases, you'd use a GET request for SELECT * VALUES from database and DELETE FROM database WHERE id = 14.

Read about CRUD

HTTP Requests

When developing fullstack, clients and servers need a way to communicate. The client would be the React app and the server being the database. Instructions are sent from the client to server via HTTP requests. This sections attempts to explain the GET method and the req.params which I recently used but may not be best practice. This section also focuses only on CUD because R has been done in fetch tutorial.

Delee is the easiest to understand. Pass it reference ID and whatever's in the database with that ID will be deleted.