DRepo: A Decentralized Version Control System- Day 3
Tags: frontend, javascript, react, ipfs
Published: 2023-12-18 19:57:32

In this section, we are going to learn the basics of JavaScript and then we will move forward to React. And at the end, we will be doing out main Project Installation Part.

## JavaScript

> JavaScript is the world's most popular programming language.
> JavaScript is the programming language of the Web.


### Why Study JavaScript?
JavaScript is one of the 3 languages all web developers must learn:

   

>    1. **HTML** to define the content of web pages
>    2. **CSS** to specify the layout of web pages
>    3. **JavaScript** to program the behavior of web pages

### JavaScript Can Change HTML Content
One of many JavaScript HTML methods is `getElementById().`

The example below "finds" an HTML element (with id="demo"), and changes the element content (innerHTML) to "Hello World":

```
<!DOCTYPE html>
<html>
<body>

<h2>What Can JavaScript Do?</h2>

<p id="demo">JavaScript can change HTML content.</p>

<button type="button" onclick='document.getElementById("demo").innerHTML = "Hello World"'>Click Me!</button>

</body>
</html>

```

### JavaScript Where To

#### The `script` Tag

In HTML, JavaScript code is inserted between 
`<script>` and `</script>` tags.

```
<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>
```

## JavaScript Functions and Events

A JavaScript `function` is a block of JavaScript code, that can be executed when "called" for.

For example, a function can be called when an event occurs, like when the user clicks a button.

## JavaScript in <head> or <body>

You can place any number of scripts in an HTML document.

Scripts can be placed in the `<body>`, or in the `<head>` section of an HTML page, or in both, depending upon the purpose or requirement.

## External JavaScript

External scripts are practical when the same code is used in many different web pages.

JavaScript files have the file extension **.js**.

To use an external script, put the name of the script file in the `src` (source) attribute of a `<script>` tag:

```
<script src="myScript.js"></script>
```

## JavaScript Output

### JavaScript Display Possibilities

JavaScript can "display" data in different ways:

- Writing into an HTML element, using `innerHTML`.
- Writing into the HTML output using `document.write().`
- Writing into an alert box, using `window.alert().`
- Writing into the browser console, `using console.log().`

## JavaScript Keywords
JavaScript statements often start with a keyword to identify the JavaScript action to be performed.

### Keyword	Description

- var	        - Declares a variable
- let	        - Declares a block variable
- const	        - Declares a block constant
- if	        - Marks a block of statements to be executed on a 
                -condition
- switch	- Marks a block of statements to be executed in 
                different cases
- for	        - Marks a block of statements to be executed in a 
                loop
- function	- Declares a function
- return	- Exits a function
- try	        - Implements error handling to a block of statements

## JavaScript Variables

In a programming language, variables are used to store data values.
JavaScript uses the keywords var, let and const to declare variables.
An equal sign is used to assign values to variables.

In this example, x is defined as a variable. Then, x is assigned (given) the value 6:
```
let x;
x = 6;
```

### Variables and Data Types
JavaScript uses variables to store and manipulate data. Variables are declared using the let or const keyword.

`let` is used for variables that can be reassigned.
`const` is used for variables that should not be reassigned.
The `let` and `const` keywords were added to JavaScript in 2015.
The `var` keyword should only be used in code written for older browsers.

```
let message = "Hello, World!";
const pi = 3.14;
let isTrue = true;
let fruits = ["apple", "orange", "banana"];
let person = { name: "John", age: 30 };
```
In the example above:

message is a string variable.
pi is a constant representing the mathematical constant Pi.
isTrue is a boolean variable.
fruits is an array containing strings.
person is an object with properties name and age.


## JavaScript Const

- Variables defined with `const` cannot be **Redeclared**
- Variables defined with `const` cannot be **Reassigned**
- Variables defined with `const` have **Block Scope**

JavaScript has two types of scope:

**Global Scope:** Variables declared outside of a function are in the global scope and can be accessed throughout the entire program.
**Local Scope:** Variables declared inside a function are in the local scope and can only be accessed within that function.


**JavaScript Data Types**

JavaScript has 8 Datatypes
1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object

> The Object Datatype
The object data type can contain:

1. An object
2. An array
3. A date


## JavaScript Functions

A JavaScript function is a block of code designed to perform a particular task.
A JavaScript function is executed when "something" invokes it (calls it).

```
function greet(name) {
  let greeting = "Hello, " + name + "!";
  return greeting;
}

console.log(greet("TDoC")); // Output: Hello, TDoC!
```
In this example, greet is a function that takes a parameter name and returns a greeting.

### JavaScript Function Syntax
A JavaScript `function` is defined with the function keyword, followed by a name, followed by parentheses ().

The code to be executed, by the function, is placed inside curly brackets: {}

```
function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
```

- Function parameters are listed inside the parentheses () in the function definition.
- Function arguments are the values received by the function when it is invoked.
- Inside the function, the arguments (the parameters) behave as local variables.

#### Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:

- When an event occurs (when a user clicks a button)
- When it is invoked (called) from JavaScript code
- Automatically (self invoked)

#### Function Return

- When JavaScript reaches a `return` statement, the function will stop executing.
- If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.
- Functions often compute a return value. The return value is "returned" back to the "caller":
```
// Function is called, the return value will end up in x
let x = myFunction(4, 3);

function myFunction(a, b) {
// Function returns the product of a and b
  return a * b;
}
```

## Control Flow: Conditional Statements and Loops

### JavaScript if, else, and else if

Conditional statements are used to perform different actions based on different conditions.

In JavaScript we have the following conditional statements:

- Use `if` to specify a block of code to be executed, if a specified condition is true
- Use `else` to specify a block of code to be executed, if the same condition is false
- Use `else if` to specify a new condition to test, if the first condition is false
- Use `switch` to specify many alternative blocks of code to be executed

### JavaScript Loops

Loops can execute a block of code a number of times.

#### Different Kinds of Loops
JavaScript supports different kinds of loops:

- `for` - loops through a block of code a number of times
- `for/in` - loops through the properties of an object
- `for/of` - loops through the values of an iterable object
- `while` - loops through a block of code while a specified condition is true
- `do/while` - also loops through a block of code while a specified condition is true

```
let num = 10;

if (num > 0) {
  console.log("Positive number");
} else if (num < 0) {
  console.log("Negative number");
} else {
  console.log("Zero");
}
```
Loops, such as for and while, enable repetitive execution of code.


```
for (let i = 0; i < 5; i++) {
  console.log(i);
}
```

This loop prints the values 0 through 4 to the console.

## JavaScript Callbacks

- A callback is a function passed as an argument to another function
- This technique allows a function to call another function
- A callback function can run after another function has finished

## Asynchronous Programming
Functions running in parallel with other functions are called asynchronous. JavaScript supports asynchronous programming to handle operations that may take time, like fetching data.

### Promises
A Promise is an object representing the eventual completion or failure of an asynchronous operation.

```
function fetchData() {
return new Promise((resolve, reject) => {
setTimeout(() => {
const data = "Fetched data";
resolve(data);
}, 1000);
});
}

fetchData().then((result) => {
console.log(result); // Output: Fetched data
});
```
In this example, fetchData returns a promise. When the data is fetched, the resolve function is called.

### Async/Await

- async makes a function return a Promise
- await makes a function wait for a Promise

```
async function fetchDataAsync() {
try {
const result = await fetchData();
console.log(result); // Output: Fetched data
} catch (error) {
console.error(error);
}
}

fetchDataAsync();
```
The await keyword is used within an async function to wait for the completion of a promise.


## 

> JavaScript EventListener



## React

- React is a JavaScript library for building user interfaces.
- React is used to build single-page applications.
- React allows us to create reusable UI components.

You can find the official **React** Documentation [Here](https://react.dev/learn)

## Setting up a React Environment

If you have npx and Node.js installed, you can create a React application by using `create-react-app`.

Run this command to create a React application named `my-react-app`:

```
npx create-react-app my-react-app
```
The `create-react-app` will set up everything you need to run a React application.

### Run the React Application

Now you are ready to run your first real React application!

Run this command to move to the `my-react-app` directory:

```
cd my-react-app
```
Run this command to run the React application `my-react-app`:

```
npm start
```
A new browser window will pop up with your newly created React App! If not, open your browser and type `localhost:3000` in the address bar.


## State and Props

State and props are two fundamental concepts in React for managing component-specific data.

### State
State is a way for a component to maintain and manage its own data.

```
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return (
      <div>
        <p>Count: {this.state.count}</p>
        <button onClick={() => this.setState({ count: this.state.count + 1 })}>
          Increment
        </button>
      </div>
    );
  }
}
```
In this example, the `Counter` component maintains its count in the state.

### Props
Props are inputs that a React component can receive.

```
function Greet(props) {
  return <p>Hello, {props.name}!</p>;
}
```
Here, the `Greet` component receives a name prop.

### Functional Components
Functional components are simple JavaScript functions that take in props and return React elements.

```
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
```

### Class Components
Class components are ES6 classes that extend from `React.Component`.

```
class WelcomeClass extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}
```
In the above examples, both components display a greeting based on the provided `name` prop.


## React Hooks

React Hooks were introduced to allow functional components to use state and lifecycle features.

### useState Hook

- The React `useState` Hook allows us to track state in a function component.
- State generally refers to data or properties that need to be tracking in an application.

#### Initialize useState
We initialize our state by calling `useState` in our function component.

`useState` accepts an initial state and returns two values:
- The current state.
- A function that updates the state.

Initialize state at the top of the function component.

```
import { useState } from "react";

function FavoriteColor() {
  const [color, setColor] = useState("");
}
```
Notice that again, we are destructuring the returned values from `useState`.

- The first value, `color`, is our current state.
- The second value, `setColor`, is the function that is used to update our state.
- Lastly, we set the initial state to an empty string: `useState("")`

```
import React, { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>Increment</button>
    </div>
  );
}
```
Here, the Counter component uses the useState hook to manage the count state.

Let's take an example of how to update a state by `useState`.

```
import { useState } from "react";
import ReactDOM from "react-dom/client";

function FavoriteColor() {
  const [color, setColor] = useState("red");

  return (
    <>
      <h1>My favorite color is {color}!</h1>
      <button
        type="button"
        onClick={() => setColor("blue")}
      >Blue</button>
    </>
  )
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<FavoriteColor />);
```

### useEffect Hook

- The `useEffect` Hook allows you to perform side effects in your components.
- Some examples of side effects are: fetching data, directly updating the DOM, and timers.

`useEffect` accepts two arguments. The second argument is optional.

`useEffect(<function>, <dependency>)`

Let's take an example and understand this.

```
import React, { useState, useEffect } from "react";

function DataFetcher() {
  const [data, setData] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      try {
        const result = await new Promise((resolve) =>
          setTimeout(() => resolve("Fetched data"), 1000)
        );
        setData(result);
      } catch (error) {
        console.error(error);
      }
    };

    fetchData();
  }, []); // Empty dependency array means it runs once after the initial render

  return <p>Data: {data}</p>;
}
```

1. **Import Statements:**
    - `React` is imported as it's required for JSX.
    - `useState` and `useEffect` are imported from React. These are Hooks used for managing state and performing side effects in functional components.

2. **Functional Component `DataFetcher`:**
    - `DataFetcher` is a functional component that fetches and displays data.
    - `const [data, setData] = useState(null);`: This line uses the `useState` Hook to create a state variable `data` initialized to `null`, and a function `setData` to update this state.

3. **`useEffect` Hook:**
    - `useEffect` is used to perform side effects in a functional component. It runs after the initial render and can be used for data fetching, subscriptions, or manually changing the DOM.

4. **`fetchData` Function:**
    - `fetchData` is an asynchronous function that simulates data fetching after a delay of 1000 milliseconds using `setTimeout`.

5. **`try-catch` Block:**
    - The `try` block attempts to fetch data and sets it using `setData`.
    - If an error occurs during the data fetching process, it's caught in the `catch` block, and an error message is logged to the console.

6. **`fetchData` Invocation in `useEffect`:**
    - The `fetchData` function is invoked inside the `useEffect` Hook.

7. **Dependency Array:**
    - The dependency array (`[]`) is empty, meaning the `useEffect` runs once after the initial render. If there were dependencies listed, the effect would run whenever those dependencies change.

8. **Return Statement:**
    - The component returns JSX that displays the fetched data inside a `<p>` element.

In summary, this component fetches data using the `useEffect` Hook, updates the state with the fetched data, and renders the data in the component. The empty dependency array ensures that the effect runs only once after the initial render.


## React Router Dom
React Router Dom is a library for handling navigation in React applications.

To add React Router in your application, run this in the terminal from the root directory of the application:

```
npm i -D react-router-dom
```

Let's take another example and understand Router-Dom.

```
import { BrowserRouter as Router, Route, Link, useParams } from "react-router-dom";

function UserProfile() {
  let { username } = useParams();
  return <h2>User Profile: {username}</h2>;
}

function App() {
  return (
    <Router>
      <div>
        <nav>
          <ul>
            <li>
              <Link to="/">Home</Link>
            </li>
            <li>
              <Link to="/user/john">User John</Link>
            </li>
          </ul>
        </nav>

        <Route path="/user/:username" component={UserProfile} />
      </div>
    </Router>
  );
}
```

1. **Import Statements:**
    - The code imports components from the `react-router-dom` library for setting up routing in a React application.
    - `BrowserRouter as Router`, `Route`, `Link`, and `useParams` are imported.

2. **Functional Component `UserProfile`:**
    - `UserProfile` is a functional component that extracts the `username` parameter from the URL using the `useParams` hook.
    - It returns an `<h2>` element displaying the user profile based on the extracted `username`.

3. **Functional Component `App`:**
    - `App` is a functional component representing the main structure of the application.
    - It uses the `Router` component to define the router context for the application.

4. **Navigation Setup:**
    - The `nav` element contains an unordered list (`ul`) with list items (`li`) representing navigation links.
    - `Link` components are used for creating navigation links. The links point to different routes, such as the home route ("/") and a user route ("/user/john").

5. **Route Definition:**
    - The `Route` component is used to define a route for the user profile. It specifies that when the URL matches the pattern "/user/:username," the `UserProfile` component should be rendered.

6. **Router Context:**
    - The entire structure is wrapped in the `Router` component to establish the router context for the application.

In summary, this code sets up basic navigation using `react-router-dom`. The `App` component defines routes, and the `UserProfile` component dynamically displays user profiles based on the username parameter extracted from the URL.


> ## Getting Started with the Project: Project Installation

After the completion of the Project, your minimized project structure should be looking like this:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/hxf6lzw4wg5offvk9yul.png)

## React Custom Package

We've chosen to create our own special toolkit (SDK) for handling IPFS uploads in our project. This decision is intentional – we're starting to use it right from the beginning. This approach makes things smoother as we progress, ensuring that the toolkit is perfectly suited to our needs for implementing the desired features in later stages of development.


You can find more about **ipfs-http-client** [Here](https://www.npmjs.com/package/ipfs-http-client).
You can find more about **Helia** [Here](https://helia.io/).

> ### thirdweb React SDK
> Ultimate collection of React hooks for your web3 apps.

You can find more about this package [Here](https://www.npmjs.com/package/@thirdweb-dev/react). 

Let’s start the project by choosing the right directory where you want to create your project and start with

```
npx thirdweb create --app
```

- Then choose create-react-app
- Then choose JavaScript