teleren/devto huggingface dataset:
When to Use Server-Side rendering vs Static Generation in Next.js
Published: 2021-12-30 19:01:11

Pre-rendering your pages has multiple benefits such as better performance and better SEO. But choosing whether to statically generate your pages or render them on the server side can be confusing.


Let's first take a look at Server-Side rendering


## getServerSideProps
The main difference between getServerSideProps and getStaticProps is when they are ran. getServerSideProps is ran when every new request is made to the page.

```javascript
export async function getServerSideProps(context) {
    const {userId} = context.params
    const user = await getUser(userId)
 
    return {
        props: {
           user
        }
    }
    
}

export default function User({user}) {
    return (
        <div>
            <h1>{user.name}</h1>
        </div>
    )
}
```

In this example we are getting the userId from a [dynamic route](https://nextjs.org/docs/routing/dynamic-routes), getting the information about the user, then using that data to build the user page.

Note that we have access to the request through params

now lets take a look at getStaticProps

## getStaticProps
We saw that getServerSideProps gets ran every time a new request is made so what about getStaticProps. getStaticProps is ran at build time, meaning that whenever you run `npm run build` this is when your static pages are built.

```javascript
export async function getStaticProps() {
    const blogPosts = await getBlogPosts()
    
    return {
        props: {
            blogPosts
        }
    }
}

export default function Home({blogPosts}) {
    return (
        <div>
            {blogPosts.map(post => (
                <h1>{post.name}</h1>
            ))}
        </div>
    )
}
```

this function is getting a list of blog posts and rendering them on a page. Because we know what we want before hand we can statically render the page whereas in our server side rendering example we don't know before the request is made what the user wants.

---
So when to user getServerSideProps?
- Good for when you don't know what the user wants before they make a request
- Still want good SEO

When to use getStaticProps?
- When we know what the user wants at build time
- Really fast performance and SEO

 
---

This was just a quick dive into static generation vs server-side generation. If you want to learn more please let me know.

As always thanks for reading.
React : PropTypes: 
Published: 2021-12-30 17:33:29

React 
**

## PropTypes: 
**
When we pass argument into the react components is called props. Props means properties.
Pass argument in component like this.
<component name ="Arif" />;
There name is attribute and arif is value of attribute.
Components receives the arguments as a props.
component(props) {
    return My name is { props.name };
  }
We can set the type of props like string , number, array, object etc.
Component.propTypes = {
    name: PropTypes.string
  };

## JSX: 
JSX stands for JavaScript XML. JSX is an extension of the Javascript language. It is based on ES6. With the help of JSX we can write HTML code in react. It makes React easier. We can write Directly HTML code with the help of JavaScript code. We write direct HTML code in the browser. But in runtime, it translates the code into JavaScript code. So JSX is Look like HTML code , but it is actually a javascript code. 

## Component Lifecycle:
React is a collection of independent component.It is run according to the interaction.React component has its own lifecycle . And there are four stage as follows, 
Initialization: In this stage with the help of props and default stage the component is created.
 Mounting: JSX is creacted and returned by render method itself.
 Updating: In this is stage where component is updated.
UnMounting: As the name suggested unmounting is the final step of the component lifecycle where the component is removed from the page. 

## Hooks: 
Hook is react new features. It is use to hook or catch state and lifecycle methods. We  need to import hook from react .
ex: 	import React , {useState} from “react”;
	function fruits(){
const [name, setName] = useState([])
return(
<h> Fruits {Name}</h>
)
}

## Context Api: 
Context API is a React structure and helps us to solve prop-drilling. The React Context API is a way for a React app to effectively produce global variables that can be passed around. This is the alternative to "prop drilling" or moving props from grandparent to child to parent, and so on. Context is also touted as an easier, lighter approach to state management using Redux. We have to import createContext from react . 
ex: 	import React, { createContext } from "react";
import useFirebase from "../../hooks/useFirebase";
export const authContext = createContext(null);
const AuthProvider = ({ children }) => {
  	const allContext = useFirebase();
  		return (
    		<authContext.Provider value={allContext}>{children}</authContext.Provider>
  	);
};
export default AuthProvider;
Creating a personal Blog in .NET 6
Tags: dotnet, javascript, csharp
Published: 2021-12-30 18:48:36

This week I created my personal blog, just to test my knowledge a little.

I made the Backend in .NET 6 using Minimal API and as a database I used SQLite together with the Entity Framework.
As a frontend I used pure javascript.
The API I published on Heroku and the blog on Vercel.

The result was the one below, if you like, feel free to copy the project.

[Source code](https://github.com/zangassis/dotnet6-minimal-blog)

It's not perfect, but it's already working properly.

Backend Minimal API:

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8wptqw62u8is3h2n2vul.jpg)

Frontend:

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


![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8yh3ilkdekfery4n286b.jpg)
CryptoPals Crypto Challenges Using Rust: Convert hex to base64
Tags: programming, rust, cryptography
Published: 2021-12-30 18:41:33

This is the [Challenge 1](https://cryptopals.com/sets/1/challenges/1) of [CryptoPals](https://cryptopals.com/) challenges implemented using Rust language.

## Context
Quite simple, we're given a hex string & have to convert it into a base64 encoded format. Basically from one encoding to another.

### Hex Encoding
[Hex](https://en.wikipedia.org/wiki/Hexadecimal) is a base 16 format using 16 symbols **0-9** and **A-F**. Each hexadecimal number (i.e. 0-9 & A-F) can be represented (or corresponds to) using 4 bits. Why 4 bits? Because, using 4 bits you can have 2^4 (=16) combinations. So, `0000 (binary) = 0 (hex)`, `1111 (binary) = F (hex)`. Consequently, two digits of hex need 4 bits. Hence, `0010 1101 (binary) = 2D`. **Note that in hex encoding there is no difference between small case letters & capital letters, they both mean same (unlike base64)**

Now, let's talk about converting an [ASCII](https://en.wikipedia.org/wiki/ASCII) text to hex. Each ASCII character is 1 byte or 8 bits of size. So, each ASCII character would require 2 digits of hex to represent! So, **Z** (in ASCII text) is **5A** in hex, and **0** (in ASCII text, not number!) is actually **30** in hex format! You can learn more [here](https://www.binaryhexconverter.com/ascii-text-to-hex-converter).

### Base64 Encoding
Similarly, [Base64](https://en.wikipedia.org/wiki/Base64) is base 64 (duh!) encoding using 64 symbols - **0-9**, **A-Z**, **a-z**, **+** and **/**. You might also see **=** chars appear at the end encoding output but **=** in base64 is just a padding applied to output to normalize output length to be a multiple of 4. Using similar logic as hex encoding above, we can see that each base64 digit represents 6 bits of data (2^6 = 64).

Theoretically, to convert hex to base64, we can first convert hex to binary to create a long string of bits (1s & 0s), divide bits into 6 bit chunks & then convert these 6 bit chunks to their corresponding base64 digits.

However, since we're using Rust, we can simplify by using two nice crates for working with hex & base64 - `hex` & `base64`.

1. First we'd convert input hex string to raw bytes using `hex::decode()`:

```rust
using hex;

let bytes = hex::decode(input_hex).unwrap();
```
2. Encode these bytes to base64 using `base64::encode()`:

```rust
using base64;

let output = base64::encode(bytes);
```
And we have the base64 `output`!

We can encapsulate it into a nice function:

```rust
use base64;
use hex;

pub fn convert_hex_to_base64(hex: &str) -> String {
    base64::encode(hex::decode(hex).unwrap())
}
```
This is it!

See the code on [Github](https://github.com/theNvN/cryptopals-crypto-challenges/blob/master/src/set_1_basics/c1_convert_hex_to_base64.rs).

Find me on:
Twitter - [@heyNvN](https://twitter.com/heyNvN)

[naveeen.com](https://naveeen.com)
How To Run Laravel Development Server On A Different Port
Tags: laravel, php, development, tips
Published: 2021-12-30 18:22:37

Normally, the development server of the Laravel runs on port `8000`, which can be accessed from [http://localhost:8000/](http://localhost:8000). But there are situations where you need to run multiple instances of Laravel applications at the same time on the same development PC. Under that kind of situation, it will not be able to start the second application as they have to use the same port 8000. So for that kind of situation, we need to use a separate port instead of the default port.

We use the Laravel Artisan command `php artisan serve` to start a development server. We can add the `--port` to mention a specific port we need to run the application. For example, if we need to run the application on port 8080 instead of the default port 8000, we can use the following command.

```
php artisan serve --port=8080
```

Now if you need to start another instance of the Laravel application, you can change the port of the `serve` command to another unused port.

If you do not like to mess with the serve command to change the port like that, you can still change the default port by using the `.env` file. Open the `.env` file in the root directory of the application and add the following line to it.

```
SERVER_PORT=8080
```

Now you can start the Laravel development server as you used to be by just using the usually `php artisan serve` command and it will start the development server with the port number you mentioned in the `.env` file.

Feel free to visit [devtonight.com](https://devtonight.com?utm_source=dev&utm_medium=questions&utm_campaign=how-to-run-laravel-development-server-on-a-different-port) for more related content.
Moving to React-Router-Dom v6 from v5 or earlier
Tags: react, javascript, webdev, tutorial
Published: 2021-12-30 18:14:17

Earlier today I was following a tutorial on React (I am quite new to React) that was made earlier in 2021. When I installed React Router and added it, I noticed that I was getting this error:

`Error: A <Route> is only ever to be used as the child of <Routes> element, never rendered directly. Please wrap your <Route> in a <Routes>.`

After researching online, I found out that the tutorial was made with React-Router-Dom v5 and the version I installed was version 6.

After a few hours of researching and debugging , I was able to get everything to work.

Your original code may look something like the following:

```
import React from 'react';
import { Container } from 'react-bootstrap';
import { BrowserRouter as Router, Route} from 'react-router-dom'
import Footer from './components/Footer';
import Header from './components/Header'
import HomeScreen from './screens/HomeScreen';
import ProductScreen from './screens/ProductScreen';

function App() {
  return (
    <Router>
      <Header />
      <main className='py-3'>
        <Container>
          <Route path='/' component={HomeScreen} exact />
          <Route path='/product:id' component={ProductScreen} />
        </Container>
      </main>
      <Footer />
    </Router>
  );
}

export default App;
```

However, in the new version of React Router, you need to wrap all the `<Route />` components in a `<Routes />` component (it replaces the `<Switch />`component).

For the Route component, it will be changed from
`<Route path='/' component={HomeScreen} exact/>
<Route path='/product:id' component={ProductScreen} />`

to

`<Route path='/' element={<HomeScreen />} />
<Route path='product/:id' element={<ProductScreen />} />`

See how the preceding forward slash in the second statement has been removed and that the colon (":") is preceded by a forward slash. Furthermore, you have `element` instead of `component`, and instead of just typing the name of the component the route is pointing to, you write it as if you are rendering it (like `<ProductScreen />`).
Another thing to note is that you don't need the `exact` property again because Route paths match exactly by default.

Also, if you want to access the parameters in the URL, you will have to import `useParams` from 'react-router-dom'

Thats all for now! Hope you enjoyed reading this.

To learn more about this, click [here](https://reactrouter.com/docs/en/v6/getting-started/installation) or [here](https://reacttraining.com/blog/react-router-v6-pre/#relative-route-path-and-link-to).
Twitter Chat: Chapter 5 Recap
Tags: bookclub, books, documentation
Published: 2021-12-30 18:06:36

<small>Cover Photo by <a href="https://unsplash.com/@chrisjdavis?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Chris J. Davis</a> on <a href="https://unsplash.com/s/photos/twitter?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a></small>

We started a book club! Each week we host a Twitter chat on Thursdays to discuss a chapter of [Docs for Developers](https://link.springer.com/book/10.1007/978-1-4842-7217-6). 

On Thursday Dec. 23rd we had our 5th Twitter chat, hosted on the [@DevEdBookClub Twitter](https://twitter.com/DevEdBookClub) account about Chapter 5. 

This post is a recap of the chat and a place to continue the conversation.

## Code Samples
**What docs or learning platforms have particularly good code samples?** 
**What do you like about them?**

[Megan Sullivan](https://twitter.com/meganesulli) showed us an example of the Gatsby docs. She liked that the Gatsby docs would include in a code sample the name of the file where the changes should go
{% twitter 1474199823356071937 %}

[Sarah Rainsberger](https://twitter.com/sarah11918) shared a link to the GraphQL tutorials on [Apollo Odyssey](https://odyssey.apollographql.com/). 
She said:
_“I love seeing code WRITTEN out, with arrows pointing to stuff bc its what I do to learn”_

{% twitter 1474199477107970059 %} 

**How do you like to learn?**

**Do you have any favorite learning platforms and if so, why do you like them?**

## Preferred Workflow
**What’s your workflow for creating code samples?**
**At what point in the writing process do you add them?**
**What tools do you use?**
**Do you prefer static or interactive code samples?**

[Ramón Huidobro](https://twitter.com/hola_soy_milk) shared that they like to prepare code samples along with the structure.
{% twitter 1474387138070425602 %}

Megan and I both agreed it depended on what we were writing. If I write tutorials I like to have a code sample written out before writing. 

{% twitter 1474202962486571010 %}
{% twitter 1474202688732602372 %}

Do you have a preferred workflow? 

## Favorite Takeaways
**What takeaways from this chapter can you apply to your own documentation practice at work?**

**Any quotes or ideas that resonate with you?**

[dvkr's](https://twitter.com/_dvkr) favorite quote was “It’s better to write looking forward than backward”. When writing code samples we should be sure we are not making it even harder for learners by adding references or examples that need shared perspective to understand. 

{% twitter 1474210152219693058 %} 

Ramón shared their favorite quote: “Explanations that accompany your samples are as important as the samples themselves”.

{% twitter 1474387872589434881 %}



## Join the Conversation 🗣
You can see the full conversation on the DevEdBookClub Twitter account. 
{% twitter 1474198195936776192 %}

Add a comment on the Twitter thread or share your thoughts here to continue the conversation. 

What did you think about Chapter 5 of Docs for Developers?
100 Days Of Learning #2022
Tags: 100daysofcode, 100daysofx, webdev, testing
Published: 2021-12-30 18:04:44

---
series: 100 Days of Learning
---
Hi there, I'm Lauren. I'm a Business Analyst working in tech and my goal for 2022 is to expand my technical skills. I'm interested in learning a lot of different things this year, from leveling up my frontend dev skills, to learning test automation, to editing videos, and more. Really I want to start doing and creating more things, rather than spending all my time scrolling social media or getting stuck in tutorial hell.

Enter my **#100DaysOfLearning challenge**! I plan to document my experience over the next few months here on Dev. 

The goal of this challenge isn't to do something every single day for 100 days. Instead, I want the spirit of this challenge to be learning and practicing new things at least 5/7 days a week, and documenting my progress. I've tried #100daysof____ challenges in the past, and not being flexible with myself ultimately resulted in me giving up on the challenge. (Another thing I'm trying out this year is #flexible goals - more on that in another post).


So here's to learning in 2022! If you're doing your own challenge, I'd love to hear about it in the comments below :-)

--------
Photo by <a href="https://unsplash.com/@chuklanov?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Avel Chuklanov</a> on <a href="https://unsplash.com/s/photos/learning?utm_source=unsplash&utm_medium=referral&utm_content=creditCopyText">Unsplash</a>
2021 in review
Published: 2021-12-30 17:58:59

2021 is almost over so time for a year end review.

##Still Virtual
For a year and 3/4 I have only been to virtual code meetups. I spent time at some outdoor events in the spring. They were not related to development but i did get to see people in person,  None of my usually meet ups have returned to in person. The few local meet ups that have are not where I can attend. My child just got vaccinated before winter break.

##Projects
Finished a python project for an improv show. Fun little side project. Take audience input and give an actor a randomized selection to pick from.
Did some React tutorials and made more CSS art for Halloween and Christmas.

##Virtual Coffee
I helped Virtual Coffee developer group by working on a Users guide to Virtual Coffee. This is a guide to help on board new members to the group. [full write up](https://dev.to/jarvisscript/coffementation-documenting-virtual-coffee-30in)


##Code Challenges

I worked on code challenges this year. I did exercises on Exercism ans a bit of [Shortcut Foo.](https://dev.to/jarvisscript/play-games-to-improve-your-developer-skills-3254)
In the spring I did the 30days of html, a humor at work challenge, and [react query week.](https://www.youtube.com/watch?v=wVvHSWFS5Go)
In September 15 days of CSS
Some of the advent of CSS. And then there's Hackoberfest.


##Hacktoberfest 2021
This is the second year I completed Hacktoberfest. I had five PRs accepted over three different open source maintainers. Most were documentation I and learned some markdown tricks.
More in this [post](https://dev.to/jarvisscript/hacktoberfest-review-18jh)

##On job search 
still looking had a good 1st round right before winter break. HR said they had a few days left to work before they shut down. Said the second round would be in the new year.

##Blogging 
After staying consistent blogging from fall 2020. I took a short blogging break for a while. It felt like I was blogging to keep a streak alive and wasn't adding much. If I had blogged more this recap would be easier. Blogging good to track progress.
I resumed in September I've blogged at least once a week since.
Vim 2022: 🍷 Play typewriter sound in Vim when you are typing a letter 
Tags: vim, linux, productivity
Published: 2021-12-30 17:35:18

---
title: Vim 2022: 🍷 Play typewriter sound in Vim when you are typing a letter 
published: true
description: 
tags: #vim,#linux,#productivity
cover_image: https://github.com/skywind3000/vim-keysound/blob/master/doc/logo.jpg?raw=true
---

It's cool to play typewriter sound in Vim when you are typing a letter. 😎

So I made a little [script] for this:

```VimL
Plug 'skywind3000/vim-keysound'
let g:keysound_enable = 1
let g:keysound_theme = 'default'

" volume range is from 0 to 1000
let g:keysound_volume = 500   
```

Then

```bash
apt-get install python3-sdl2
```

Make sure that your vim has `+python3` feature enabled.

And you go.

See this video by Keefle (there is no audio delay in reality).

- https://streamable.com/yah0h
How JWT Works
Published: 2021-12-30 15:32:05

Nowadays we are progressing to investigate a really curious subject called JWT!! Its full form is Jason web token. So what is actually JWT, you may be wondering. Well it could be a basic however an awfully solid way of confirming a client of any JSON information. This approach is exceptionally accommodating amid two party interaction. We might need to confirm the individual whom the information is sent to. JWT saves us from the rehashed activity of sending private information on each ask. Life gets a bit easier with this.

So how does JWT work? It is fundamentally an encoded URL string that can contain any sum of information and it is made secure by making it cryptographically marked. Servers by and large utilize these tokens and they can name it as trusted as the information has been marked from the source. No other party in between can get to to it or alter it.

In any case, the information we are sending it is as it were confirming the proprietorship of the information. In case any one alters the information they can effortlessly see the information we are sending. It is since the information is serialized and the information is still not scrambled. To form the information secured we ought to scramble the information. So to overcome this circumstance it is prescribed to utilize JWT with HTTPS.

This is often how a JWT token looks after encryption. No one can adjust this let alone examine the data unless they interpret it. In spite of the fact that, we are able utilize JWT.io to interpret this data. JWT contains 3 parts: header, payload and signature. Header contains the data of the sort of ask and hashing calculation data. Payload is where all the information which we are sending. At last signature is utilized to send a mystery key. The mystery is the Signature held by the server in order to confirm tokens and sign unused ones.

We now know what JWT really is, its reason and what kind of data does JWT hold. Now lets see how the method happens Lets consider a situation where a client sends login request with there information. The server verifies the client and after that assigns it a token that contains the user's character. The token consequently is spared into neighborhood framework when that client enters the application. Presently when the client demands for anything that token is included with the ask and sent to server. The browser at that point checks for tokens and in case found confirms the client and approves the client to get to to the asked information.

This steps are continuously genuine for any kind of demands client makes interior the application. At last when the client logs out the token is removed from the nearby framework automatically. JWT makes server to server authorization simple. Be that as it may we ought to not utilize it as session token as JWT has expansive scope and there are rear ways to form botches. Besides, ready to not expel the tokens at the conclusion of the session as there's no central specialist to discredit them. We moreover should not utilize it with treats because it will increment the estimate of the overhead of the ask.