teleren/devto huggingface dataset:
Client-Side Routing vs. Server-Side Routing with React Router
Tags: webdev, react, routing, javascript
Published: 2022-05-13 18:55:46


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oktqpdbb79t30sdjwrrz.jpeg)
If you are going to be building websites, it's clear you will need to learn routing. It is fundamental in web development and nearly every site you visit will change it's URL as you navigate through the site. When first learning React and creating single page applications, you will see that creating routes is not required to make a functional application. However, once you discover routing, you will never not use it again.

While all websites are connected to a server and a lot of the time routing is handled server-side, frameworks like React have great ways to also handle routing client-side.

## So, what is routing?
Routing is the mechanism by which requests are routed to the code that handles them. These requests are specified by a URL and protocol method(HTTP). Essentially, you the router will determine what will happen when a user visits a specific URL. 

Sound familiar? We see this every day when browsing the internet.

## Server-Side Routing
Server-side routing is still the most common way of handling requests. 
Server-side routing looks like this:

- A user clicks a link that requests a new page and new data from the server.
- The server responds with the requested content.
- The content refreshes on the browser.
- The URL is updated to reflect the request and content on the browser.

## Client-Side Routing
Client-side routing is when the route is handled by the Javascript that is loaded to the page. It's process differs from server-side routing. Let's take a look:

- A user clicks a link and the URL changes.
- The URL change represents the state change in the application.
- NOTE: The whole page does not refresh. Only the component/data with a state change re-renders.

## React Router
When using React, we have access to an amazing library called React Router. React Router allows us to do both server-side and client-side routing. 

So which routing method should we use? Well, each has it's pros and cons. There's no best method to how you route, and you will need to decide which method best fits your needs.

Typically client-side routing is preferred for fast routing between components, since less data is loaded on each change. Server-side routing is fast on page load, and you will get the exact data you requested. Most browsers are optimized for server-side routing because it has been the more common method for a longer period of time. 

Do you want client-side routing?
All you need to do is install the library and wrap your content in the `<BrowserRouter>` tag, and then create some Routes.
Then, `<Link>` is used to set the URL and keep track of browsing history.

Do you want server-side routing?
Instead of wrapping your content in the `<BrowserRouter>` tag, you  need to use the `<StaticRouter>` tag and use ReactDOMServer.renderToString instead of ReactDOM.render.

For more information, check out the docs: [https://reactrouter.com/docs/en/v6](https://reactrouter.com/docs/en/v6)
Phase 2 - First Time Learning React
Tags: react, programming, webdev, discuss
Published: 2022-05-13 18:47:52

Learning React was very exciting due to the fact that I have been hearing about its popularity on the web. Before I started learning React, I was really curious about what React is and does.
React is a JavaScript library for building user interfaces (source: [React docs](https://reactjs.org/)). Simply put, a JavaScript library is reusable codes written by someone else that is used to help solve common problems that developers face. Out of many great features of React, I learned that React allows you to write code Declaratively meaning you describe what a goal or result a program should accomplish instead of describing each action a program should take. This enables us to write codes more predictable and easier to manage debugging (source: [React docs](https://reactjs.org/)). Also, I learned that React is component-based meaning you build blocks that handle their own data and UI logic. I felt that writing a function that takes parameters in JavaScript in Phase 1 definitely helped make it easier for me to understand writing React’s Components. Writing JSX (an extension of vanilla JavaScript with specific syntax that looks similar to HTML) in components just made codes look easy to follow.  During the phase 2 learning react, I learned how to create components, pass data to children components using props, use useEffect to fetch the data from the server,  use useState dynamically to change the data as users interact with our application, make control components, handle events, use client-side routing and put together to make a web application using React. I believe that the reason I was able to easily conquer Phase 2 code challenge the first time was not only that React was efficient to learn and use but also that understating JavaScript made it easier for me to learn React.  The most important part of learning React was that it made me realize that having strong and solid JavaScript knowledge would only benefit me in my future career as a developer!
Top 3 Coding Tutorials of the Week
Tags: elixir, python, javascript, tutorial
Published: 2022-05-13 18:43:29

Happy Friday everyone! 😌

Every Friday at [CodeCast](codecast.io) we give love to our Top 3 Casts of the week. We're lucky to have some fantastic creators producing great tutorials for us. This week we're featuring content on Elixir, Web Security (with Python), and Building a Chrome Extension! So without further ado...

![Let's Go GIF](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ugvxzqtop3f3mntyydy6.gif)
 
## [Elixir: The |> Operator](https://www.codecast.io/casts/eG2p1vW0QZ31-learn-with-me-intro-to-elixir-lesson-ten-the-operator-homework) by [@amy](https://www.codecast.io/users/amy)

![Elixir Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x8vhot286608eo8s84en.png)
 
Our founder Tam has created a [7-hour introductory course on Elixir](https://www.codecast.io/series/58-intro-to-elixir) and most of the videos end with exercises to do on your own time. Amy has created her own series working through these exercises, and this tutorial goes over the exercises working with the `|>` operator.

## [Server Side Request Forgery](https://www.codecast.io/casts/9yNpJ1W05v2l-server-side-request-forgery-web-security-with-python) by [@jesusvilla](https://www.codecast.io/users/jesusvilla)

![Server Side Request Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/qnlbz7v4jnxjk83aw1nx.png) 
 
Jesus is a security engineer and is passionate about showcasing weak spots and flaws so you can write stronger, more secure code. This Cast focuses on how you people can trick the server into making requests it shouldn't!

## [Procrasti..nator: Chrome Extension: Introduction](https://www.codecast.io/casts/3lw5Y8mxLgyW-procrasti-nator-chrome-extension-introduction) by [@kauress](https://www.codecast.io/users/kauress)

![Chrome Extension Cover](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8glzg3lb8ajnzhawnlzp.png) 
 
Chrome extensions are very popular and can be incredible tools. Google has an entire Chrome Extension API with fantastic docs to help you develop your own Chrome extension. In this first part of her course, Jannat goes over what you'll be creating!
Hello World in java swing...
Tags: java, swing, hello, world
Published: 2022-05-13 18:42:02

Hello guys today i am going to show you how you can print "Hello World" in java swing.

Now, what is java swing?

ANS : Swing is a GUI widget toolkit for Java. It is part of Oracle's Java Foundation Classes (JFC) – an API for providing a graphical user interface (GUI) for Java programs. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit (AWT)

Let's get started...

First of all you need to create a general class inside you package.

```java
package com.hakim;

public class HelloWorld {
    public static void main(String[] args) {
       
    }
}

```
Then you need to import `JOptionPane` from 'javax.swing' package.

```java
import javax.swing.JOptionPane;
```
Then you need to write this line in your main method.

```java
 JOptionPane.showMessageDialog(null,"Hello World.");
```

That is it.Easy,Right?
Dockerizing DevOps V2 - AzDO container jobs
Tags: devops, docker, devcontaine
Published: 2022-05-13 18:04:10

This is a follow up to my previous blog post of [Dockerizing DevOps](https://dev.to/eliises/dockerizing-devops-39hk), because I've discovered a better way to run containers within AzDO by using [container jobs](https://docs.microsoft.com/en-us/azure/devops/pipelines/process/container-phases?view=azure-devops) with [step targeting](https://docs.microsoft.com/en-us/azure/devops/pipelines/process/tasks?view=azure-devops&tabs=yaml#step-target):

```yml
trigger: none

resources:
  containers:
    - container: devcontainer
      image: $(imageRepository):$(Build.BuildId)
      endpoint: demoacr
      options: --name devcontainer

variables:
  - name: dockerRegistryServiceConnection
    value: "demoserviceconnection"
  - name: imageRepository
    value: "demoacr.azurecr.io/foo-devcontainer"

stages:
  - stage: BUILD
    displayName: Docker build & push
    jobs:
      - job:
        displayName: Devcontainer build & push
        steps:
          - task: Docker@2
            displayName: Login to ACR
            inputs:
              command: login
              containerRegistry: $(dockerRegistryServiceConnection)

          - task: Docker@2
            displayName: Build and push an image to container registry
            inputs:
              command: buildAndPush
              repository: $(imageRepository)
              dockerfile: ".devcontainer/Dockerfile"
              containerRegistry: $(dockerRegistryServiceConnection)
              tags: |
                $(Build.BuildId)
                latest

  - stage: TEST
    displayName: Run tests and linters
    dependsOn:
      - BUILD
    jobs:
      - job: Tests
        steps:
          - task: Docker@2
            displayName: Login to ACR
            inputs:
              command: login
              containerRegistry: $(dockerRegistryServiceConnection)

          - script: |
              make lint
            displayName: "Lint"
            target: devcontainer

          - script: |
              make test
            displayName: "Run all tests"
            target: devcontainer

```
Why I'm starting a blog?
Tags: beginners, writing
Published: 2022-05-13 18:00:56


I've never been a keen reader, nor was I writing somehow. Linguistics has always been one of my deficiencies. But now, I'm going to start a blog. Sounds paradox, it is.

> The best time to plant a tree was 20 years ago. The second best time is now - Chinese proverb


Over the last year, I made experiences and developments that convinced me to do this. I want to give two insights of mine to draw a picture of what first dissatisfied me and finally persuaded me.

Last summer, I started some online curriculum in programming. I wanted to graduate on a specific goal/course. There were four classes to pass, each scheduled for four months at 10 hours of studying per week. Proudly achieving my ambitious goal, I recognized that I was on the fast track. Unfortunately, I applied my habitual study style rooted in my times at school/university. I focused just on finishing projects. Certification was the purpose, not the knowledge. I had never learned a proper way to study.
Too many things I need to look up. Of course, regular and more often use of the new knowledge will stop that, and I'm now able to look up things related to an issue. But I'm convinced there is a more effective way of learning.

At the same time, I spent a several hours a day listening to podcasts and reading stuff about Bitcoin. A new passion. I soaked up all information I could find about it. When listening and reading several facts were perspicuous and some need more investigation. With time I built a solid understanding but trying to share my new knowledge was far more complicated. I remembered basic facts but was not able to connect all the dots to convey the whole picture.
I recognized again that I must figure out a method to improve my learning strategy.

The solution I'm looking for is writing. Re-writing is rethinking. It's the opportunity to reflect on new information and build a stronger fundamental. Through writing, I'm going to improve and deepen my learning and understanding.

![WritingconnectsTheDots](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/vkbc3805w3b8l85va2un.jpeg)

But why doing in public through a blog? Because I want to have some skin in the game. It forces me to be clean. The double-checking of my works accelerates the learning process even more. And hopefully, I can attract like-minded intellectual sparring partners, who are willing to question, criticize, and pressure test my thinking.

Finally, my challenge is on. My first Blog is done. More to come ...
Embedded videos with react but make it easy.
Tags: react, javascript, webdev, programming
Published: 2022-05-13 18:00:33

For my react based project for school, I decided to go way in over my head with routing, embeds, and functionality considering I only had about 3 days to finish it... but one of the big features I wanted to include was creating a route to a page with an embedded YouTube video playing a trailer for the specific documentary that was selected on the home screen. Now how did we accomplish this?

For starters: Routing. We created our routes, and instead of placing the route to the page with all of the trailers on one page we passed the links to the trailers down through a props and tagged the route on the images with a link tag.

`<Link to={`/youtube/${embedId}`}>
        <img src={docInfo.image} alt={docInfo.comment} />
        </Link>`

And the rest of the routing inside of your App.js component...

`  return (
    <>
    <Header search={search} handleSearch={handleSearch} />
    <Switch>
    <div className="app">
    <Route path='/newdocform'>
      <NewDocForm addNewDoc={addNewDoc}/>
    </Route>
      <Route exact path="/">
      <DocuContainer
        natureDocs={displayedListings}
      />
      </Route>
      <Route  path='/youtube/:embedId'> 
      <Trailer />
      </Route>
    </div>
    </Switch>
    </>
  );`

Once you have you route tagged on to the image and have built out the rest of your routing you should be able to route through your webpage by clicking your images!!

Now here comes the easiest part: embedding videos.

Embedding is was easier than you think. For one, YouTube specifically has an embed option for using their videos with all the code you need for example:

`<iframe 
width="560" 
height="315" src="https://www.youtube.com/embed/QjVLMU9MdOY"
title="YouTube video player" 
frameborder="0" 
allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>`

The type of tag that you need to make everything function properly is an <iframe>. iframes work by creating a space within your site that allows a separate document to be displayed within your webpage without needing to redirect. You can also make iframes dynamic.

For my project, we decided to dynamically render the videos within the routing so we changed our SRC from

`src="https://www.youtube.com/embed/QjVLMU9MdOY"`
(this link is just to the Monterey Bay Aquarium jellyfish tank)

to

`src={"https://www.youtube.com/embed/${embedId}"}`

The reason we did that was because when you click the image and you are routed to the page that contains your trailer, we don't want every single trailer to render and we also didn't want only one trailer to render. All together it makes the routing more dynamic and more flexible and also it allows you to pull more complex APIs and include more information in to your webpages. It can help level up your code and it also makes it easier to embed things instead of having to recode out everything to include more complex coding structures. Might as well include things the easy way!
Function Composition in Javascript
Tags: javascript, dsa, algorithms, webdev
Published: 2022-05-13 17:41:29

> _Function composition is an approach where the result of one function is passed on to the next function, which is passed to another until the final function is executed for the final result_.


![Function Composition](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/f4d9ae59r9as8a8v68nr.png)
 
Example:

```
const square = x => x*x;

const addTen = x => x + 10;

const result = compose(square, addTen)(20);
result: 410;
```

Lets write the **compose** function for the above question..

```
function compose(f1, f2){
  return function(value){
      return f2(f1(value));
  }
}
const result = compose(square, addTen)(20);
```
if we console log the **result**, the answer would be 410.

However, the solution above is only valid if compose accepts no more than two functions. So, to make it work for an n-number of functions, we need to make a few changes.

```
function compose(...args){
  return function(value){
      return args.reduce((pre, current) => current(pre), value);
  }
}
const result = compose(square, addTen, addTen, addTen)(20);
answer: 430.

// here were are using rest operator ...args to accept n-number of arguments in an array.
args.reduce() will iterate over each element/function with the previously computed value, returning the final computed value.
```

The function above can be shortened as below:

```
const compose =(...args) => value => args.reduce((pre, current) => current(pre), value);
const result = compose(square, addTen, addTen, addTen)(20);
answer: 430.
```

I hope this helps you solve such a problem during your interview.

Thats all for now. Keep learning and have faith in Javascript❤️
Immersive Communities a Social Media Platform for Content Creators
Tags: socialmedia, contentcreators, writing
Published: 2022-05-13 17:59:22

Hi everyone, I’m Mario, the creator of [Immersive Communities](https://immersive.community).

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

I’ve been working in my spare time as s solo-developer on this project for the last 4 years and finally completed it last month.

## Immersive Communities is a social media platform for content creators where they can create and monetize their own communities and collaboratively write articles about their interests. 

Each community can be monetized with member subscriptions and self-service ads. Payments have been implemented with Stripe.

A user can register a community from the main page and it will be available on the subdomain of his choice. I chose the PWA-first approach so each community is installable on desktop or mobile and behaves as a full-screen app. As you can see, the design is optimized for both desktop and mobile. The navigation bar will change its position according to the size of the screen. This was done using Tailwind CSS. 

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

## A user can register a community from the main page and it will be available on the subdomain of his choice. 

I chose the PWA-first approach so each community is installable on desktop or mobile and behaves as a full-screen app. As you can see, the design is optimized for both desktop and mobile. The navigation bar will change its position according to the size of the screen. This was done using Tailwind CSS. 

Articles are written in Markdown by default and can be linked together to form a knowledgebase like Wikipedia. Each community has its own search function which is build with Algolia. For each article we also have recommendations, done with Recombee.com, to show more articles so the user will have a Pinterest-like experience while reading. Each article also supports adding images using Cloudinary and embedding of links using Embed.ly.

Members can also communicate using real-time messages, which was done in Twilio. The community is localized in 10 languages using Locize.com. The rest of the backend was built and unified on AWS using serverless architecture.

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

Feel free to check it out and let me know if you have any questions.
Error hierarchies and Kotlin sealed interfaces
Tags: kotlin, android
Published: 2022-05-13 17:59:21

---
title: Error hierarchies and Kotlin sealed interfaces
published: true
date: 2022-05-13 17:57:30 UTC
tags: Kotlin,Android
canonical_url: https://www.rockandnull.com/kotlin-sealed-interface/
---

 ![Error hieranchies and Kotlin sealed interfaces](https://images.unsplash.com/photo-1472141521881-95d0e87e2e39?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&ixid=MnwxMTc3M3wwfDF8c2VhcmNofDF8fGNhdGVnb3JpZXN8ZW58MHx8fHwxNjUyNDY0NTUx&ixlib=rb-1.2.1&q=80&w=2000)

In a previous post, I covered what I consider a pretty useful feature of Kotlin: [sealed classes](https://dev.to/mavris/kotlin-sealed-class-primer-3oh3-temp-slug-6384139).

These classes can be quite useful when modeling errors in Android apps (and beyond). But they have their limitations. Classes, as you probably know, in Kotlin can only extend a single class. What happens, in the relatively common scenario, where an error belongs to multiple error "categories"?

Enter sealed interfaces. A class can implement multiple interfaces. So if the error "categories" are defined as sealed interfaces, a concreate error can belong to multiple "categories".

```
sealed interface ExpectedError
sealed interface UserError
    
data class InvalidUserError(val id: Int): UserError, ExpectedError // 1.
data class InvalidArgumentError(val message: String): ExpectedError
    
fun handleUserError(error: UserError) { // 2.
    TODO() 
}
    
fun handleExpectedError(error:ExpectedError) { // 3.
    when(error) {
        is InvalidArgumentError -> TODO()
        is InvalidUserError -> TODO()
    }
}
```

1. A single error can belong to multiple "categories".
2. And you can handle the error "category" as a whole or ...
3. ... handle each error specifically using the `when` statement.

But what's the benefit over defining a normal interface? Remember that you can define subclasses of sealed classes and interfaces only in the same Kotlin module. This limits the scope where these hierarchies can be extended (i.e. in the same module) and therefore limits the misuse surface.

Although this might seem like a simple feature, it opens the way for defining comprehensive error hierarchies. Hopefully, you can use it to make your codebase a bit tidier and a bit harder to misuse.

Happy coding!