teleren/devto huggingface dataset:
React Hook Form - Combined Add/Edit (Create/Update) Form Example
Tags: react, javascript, webdev, typescript
Published: 2022-10-14 15:59:45

Today we are going to perform a crud app where we will add and edit the form with same component .
We will use react-router-dom , formik and yup. so let's dive to the code.

Create a component as AddEdit.js

```
import React, { useEffect, useState } from 'react'
import { Formik, Form } from 'formik'
import { useMutation, useQuery, useQueryClient } from 'react-query'


const AddEdit = () => {

  const history = useHistory()

  const user = useUser()

  const params: any = useParams()

  const queryClient = useQueryClient()

  const id: number = Number(params?.id)

  const isAddMode = !id

  const { data, isLoading, isError } = useQuery(['data', id], () => getData(id), {
    enabled: !!id,
  })

  const onFormSubmit = (values: any) => {
    isAddMode ? addFnc : editFnc
  }

  const initValues = {
    name: isAddMode ? '' : data?.name
  }

  return (
    <>
      <div className=''>
        <Formik validationSchema={Schema} initialValues= {initValues} onSubmit={onFormSubmit}>
          {(props) => (
            <Form className='w-100 pb-10'>
              <Field name="name" />
              <button
                type='submit'>
                  'Submit'
              </button>
            </Form>
          )}
        </Formik>
      </div>
    </>
  )
}

export default AddEdit
```
So here , we created a function and hence we added the code.
Clean Code Tip: Keep the parameters in a consistent order
Tags: cleancode
Published: 2022-10-14 15:49:00

If you have a set of related functions, use always a coherent order of parameters.

Take this _bad_ example:

```cs
IEnumerable<Section> GetSections(Context context);

void AddSectionToContext(Context context, Section newSection);

void AddSectionsToContext(IEnumerable<Section> newSections, Context context);
```

Notice the order of the parameters passed to `AddSectionToContext` and `AddSectionsToContext`: they are swapped!

Quite confusing, isn't it?

![Confusion intensifies](https://media.giphy.com/media/yZ2FSn86bf2co/giphy.gif "Confusion")

For sure, the code is harder to understand, since the order of the parameters is not what the reader expects it to be.

But, even worse, this issue may lead to hard-to-find bugs, especially when parameters are of the same type.

Think of this example:

```cs
IEnumerable<Item> GetPhotos(string type, string country);

IEnumerable<Item> GetVideos(string country, string type);
```

Well, what could possibly go wrong?!?

We have two ways to prevent possible issues:

1. use coherent order: for instance, `type` is always the first parameter
2. pass objects instead: you'll add a bit more code, but you'll prevent those issues

To read more about this code smell, check out [this article](https://maximilianocontieri.com/code-smell-87-inconsistent-parameters-sorting "Inconsistent Parameters Sorting | Maximiliano Contieri") by Maxi Contieri!

_This article first appeared on [Code4IT](https://www.code4it.dev/)_

## Conclusion

To recap, always pay attention to the order of the parameters!

- keep them always in the same order
- use easy-to-understand order (remember the Principle of Least Surprise?)
- use objects instead, if necessary.

👉 Let's discuss it [on Twitter](https://twitter.com/BelloneDavide/status/1441462443364864006 "Original post on Twitter") or in the comment section below!

🐧
Luos update promises to save space on MCU's at the edge
Tags: opensource, programming, microservices, luos
Published: 2022-10-14 15:47:38

Abhishek Jadhav wrote an article for EDGEIR to present our new release requested by our community. 

[▶️ read](https://www.edgeir.com/luos-update-promises-to-save-space-on-mcus-at-the-edge-20221005)
 
An update that aims to reduce the amount of space required on MCUs with limited resources while giving users more flexibility in choosing which MCU to use.

The article also puts a focus on our Discord community, on Nimbl’bot and on our SimpleFOC new integration.
HacktoberFest Update
Tags: hacktoberfest
Published: 2022-10-14 15:37:46


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

This is my first year participating a project and i have successfully completed it.

Want to participate in more fest and programs like this looking for more opportunities...
React Hooks : How to use Authorization in react js with custom hook.
Tags: javascript, react, webdev, auth
Published: 2022-10-14 15:31:35

## Here today I am gonna use custom hook and create a authorization for admin and other manager roles.

Lets start by creating a custom hook as useUserRole.js

```
import {useEffect} from 'react'
import { toast } from 'react-toastify'

import {useAuth} from './useAuth'

export const useUserRole = (allowedRoles) => {
  const {session} = useAuth()
  useEffect(() => {
    if (!allowedRoles.includes(session?.user?.role)) {
      localStorage.removeItem('session')
      window.location.reload()
      toast.error(`Unauthorized`)
    }
  }, [allowedRoles , session])
  return true
}
```

here , we created an custom hook that takes allowedRoles and we are checking the allowedRoles with the role on our session during the login

here the condition is , if the allowedRoles is equal to the role in session then they are allowed to view the provided route else they will be redirect to login page.

Now we can specify the roles.

```
export const ROLE = {
  Admin: 'Admin',
  Manager: 'Manager',
  User: 'User'
}

```
 Now in any component like Blog.js

```

import React, { useState } from 'react'

import { useUserRole } from '../../../hooks/useUserRole'
import { ROLE } from '../../../_helpers/Role'

const Blog = () => {

//checking the role
  useUserRole([ROLE.Admin]);

  return ( 
        <>Blog page</>
  )
}

export default Blog
```

## Conclusion
  
   Hence , the authorization is success and hence we can reuse the hook for the protected routes.
Being a Developer Advocate: Week Six
Tags: devrel, learninpublic
Published: 2022-10-14 15:01:47

We did our first Developer Experience Audit today with a new hire! 🥳

Seeing someone struggle starting from your landing page through your documentations _Getting Started_ is something else.

It gives you a completely different view where users get stuck or frustrated and what you need to change so they can succeed.

## Writing an Article for Print and Endless Content Creation Ideas

We committed to writing an article for print which is based on the talk [The Future of UI Testing](https://bit.ly/3rKdIdO). This is a great way to recycle content and enrich it with more details.

So the first thing I did was to create a blog series out of it to get an idea of how the content should be structured.

I then began to write the print article with all the requirements that come with it (Vector graphics, count of characters, stylistic recommendations, etc. pp). Writing it for print took me about two days in total. That seems like a lot, but for me, print sets a much higher bar in quality 🤓

## Using Grammarly to Check Your Writing
I also gave Grammarly another shot and it really helps with my Writing. Being a non-native speaker it is hard to get punctuation right. Struggling with declination is another specialty of mine 😅 And of course the usual spelling mistakes.

Grammarly helps with all of that! 🥰

## Recommended Reading
Recycling and expanding on already existing content is a great way to come up with ideas. [Stephanie Morillo](https://changelog.com/person/radiomorillo) wrote about it in her excellent blog [4 sources of endless content ideas - article](https://changelog.com/posts/4-sources-of-endless-content-ideas)
Bitpowr & Polygon
Published: 2022-10-14 14:40:23

## Now you can securely access and interact with Polygon on Bitpowr.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/n3vxhv8dp6uz33qf5dx9.jpg)
**On-Chain transaction**

You can securely carry out on-chain transactions with the following polygon assets (MATIC, USDC_MATIC) between wallets on Bitpowr.

**Smart contract wallet**
We also support Polygon (Mainnet, Mumbai) on our smart contract wallet, where you can deploy, flush, and auto flush tokens. This is an on-chain non-custodial smart contract wallet designed to cut transaction fees and simplify user onboarding in web3 apps with multiple chains

**What Is Polygon (MATIC)?**
As the world’s second largest cryptocurrency, Ethereum has a lot of potential. However, the real value of this blockchain lies in its ability to scale and interoperate with other blockchains. Polygon allows developers to build decentralized applications (DApps) on top of Ethereum without having to worry about scaling issues; it does so by creating smart contracts that are able to run on multiple nodes in parallel without any coordination between them.

**What is Polygon?**
Polygon is a cryptocurrency, with the symbol MATIC, which is used for governance, staking, and fee payments on the Polygon network (which means that MATIC holders get to vote on changes to Polygon). MATIC can be traded on different exchanges
Polygon The goal of Polygon is to create an open-source smart contract based on Ethereum. This allows users to build their own decentralized applications (DApps) using their own custom code. It also has built-in support for common functions like consensus algorithms and identity management systems.

**How Does Polygon Work?**
Polygon is built on a new consensus algorithm called Proof of Correctness (PoCo) and is used to verify transactions. PoCo is a hybrid of PoW and PoS, which makes it more efficient than either one alone. In addition, it uses less energy because miners don’t need to spend money on electricity or hardware to mine blocks anymore; instead, they can earn tokens by validating transactions in the network using their computer’s processing power alone.

As you might expect from an “easy” cryptocurrency like this one—which gives users an option between getting paid immediately or waiting up to three days before receiving payment—polygons are designed so that they can be easily mined by anyone who wants them: all you need is access to your own computer (or smartphone).

**Conclusion**
In conclusion, Polygon is a great project and an important step for the Ethereum community. Scalability is a pressing issue in this time of growing interest in blockchain technology, and with Polygon, there will be more transactions per second on the Ethereum network than ever before. We are happy to support Polygon on the Bitpowr network. [Get access here](https://bitpowr.com/contact-sales#contact)
Bitpowr & Solana
Published: 2022-10-14 14:37:43

**Securely Integrate Solana into your product.**

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

## Bitpowr & Solana
We’re pleased to announce that Bitpowr now supports Solana. Via Bitpowr, you can now store, transfer and launch products that interact with Solana’s native SOL tokens and SPL tokens, which are created on the Solana blockchain.

**How does Solana work on Bitpowr:**
For instance, if Peter wants to send USDC to anyone in the world, he should be able to do so using the Solana Blockchain integrated in Bitpowr (transactions on solana are faster and cheaper). He can fund his Bitpowr wallet with USDC _SOL via wire transfer or Silvergate Exchange Network (SEN), after which he will be able to carry out on-chain transactions with ease.

**Overview of Solana**
Solana is a blockchain platform designed to run decentralized applications. Based on proof of History (PoH) and proof of Stake (PoS), it processes transactions quickly at low cost.

To pay for network transaction fees, Solana has its own native and utility token called SOL. Additionally, it is employed for staking, which enables users to assist Solana’s security while gaining rewards. The inflationary token is designed to have a decreasing supply and an annual inflation rate of 1.5%. Solana is an ideal ecosystem for many DApps and other DeFi applications since the blockchain is faster and cheaper.

Get started

If you are an existing Bitpowr users go to your wallet dashboard and create a new SOL wallet. Connect with our team if this is your first time or you need more information
Ethereum Security Data Collection Ideas - DSPYT
Tags: ethereum, tutorial, blockchain, news
Published: 2022-10-14 14:21:18

The systematic process of obtaining observations or measurements is known as data collection. Data collection allows you to gain first-hand knowledge and unique insights into your research problem, whether you are conducting experiments for commercial, governmental, or academic purposes. Although methods and objectives differ between fields, the general data collection procedure is the same.

Full-article:
https://dspyt.com/data_collection_ideas

Video on the article to YouTube:
{% embed https://youtube.com/watch?v=Bpiu_vVFdTE&feature=share&utm_source=EKLEiJECCKjOmKnC5IiRIQ %}

## About Dspyt Channel:
We are Data Science with Python DAO
[Dspyt Homepage](https://dspyt.com)
[GitHub DAO Page](https://github.com/dspytdao)
HacktoberFest Update
Tags: hacktoberfest
Published: 2022-10-14 14:15:15

We're two weeks into Hacktoberfest. I thought I would post a quick update on my progress.


![wire frame sphere. text says happy hacking.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cdnyazaxzxkw62m7b1zx.jpg)

## Contributor.
1 Pull request accepted and matured.
1 Pull request merged and maturing.
2 Pull Requests pending
1 issue assigned but waiting for maintainer to finish something before I can add my part.

## Maintainer.
This is first year maintaining a project. So far I had 3 new to Hacktoberfest PRs accepted and a fourth assigned. Of these two wrote their own issue one was their first issue ever written.
Bitpowr & Celo
Published: 2022-10-14 14:08:38

**Easily interact with Celo on Bitpowr**

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

## Bitpowr & Celo
You can now directly transact, store, transfer or build with Celo (MAINNET, TESTNET ) on Bitpowr.

Bitpowr also provides token support with CELO, cUSD, and cEUR for retail customers through Rest API.
You can also store and transfer CELO, cUSD, cEUR from your Bitpowr Vault.
How does Celo Work on Bitpowr?

For Instance, User A is a user on Bitpowr and he wants to send Celo to User B
The acceptance criteria is that User A must have his Celo asset to be funded.
User A will then request for User B Celo address.
User A will now proceed with on-chain transaction of the amount of Celo he chooses to send to User B.
These criteria works also for cUSD and cEUR on Bitpowr

## What Is Celo?
Celo is a platform that enables mobile users all over the world to perform easy financial transactions using cryptocurrency.

It uses a consensus algorithm based on Proof-of-Stake (PoS). In comparison to Proof-of-Work (PoW) systems such as Bitcoin, this eliminates the negative environmental impact and allows users to perform transactions that are cheaper, faster and immutable transactions.

Celo Mento stablecoins are Celo Dollars (cUSD), Celo Euros (cEUR) and Celo Reals (cREAL). These stablecoins allow you to share value faster, cheaper, and more easily. They instantly unlock access for everyday uses like low-cost remittances and cross-border payments, global distribution of charitable aid, effortlessly paying online, or transferring value within exchanges, particularly in markets subject to currency volatility.

Celo gives you the tools you need to easily integrate DeFi into your existing mobile app or blockchain business. Using their worldwide financial infrastructure, you can receive payments, send payouts, and manage all of your DeFi needs.

[Get started with Celo here
](https://bitpowr.com/contact-sales)
What was your win this week?
Tags: discuss, weeklyretro
Published: 2022-10-14 14:04:04

---
title: What was your win this week?
published: true
description: Got to all your meetings on time? Started a new project? Fixed a tricky bug?
tags: discuss, weeklyretro
cover_image: https://cl.ly/188e843c2985/download/Image%202019-02-15%20at%202.36.37%20PM.png
---

Hey folks! 👋

Hope everybody is having a fantastic Friday and that you all have wonderful weekends!

Looking back on this past week, what was something you were proud of accomplishing?

All wins count — big or small 🎉

Examples of 'wins' include:

- Starting a new project
- Fixing a tricky bug
- Taking a long bike ride 🚲

---

Y'all be good!

![Lisa Simpson dancing on an all black background with a kaleidoscope of colors flying around behind here, the words "THAT FRIDAY FEELING" appear beneath here](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ewko7s40ag86ziv5xe6y.gif)
Think Like A Dev
Tags: programming, webdev, beginners, career
Published: 2022-10-14 13:53:08

Things have been pretty busy, and I want to sit back down and write some more posts soon. But in the mean time, I wanted to share some exciting news about one reason I’ve been so busy!

I’ve been working with Maven, a company that specializes in live community-based courses, to develop a 2-week intensive to help early-in-career developers learn the essentials about what it means to be a software engineer.

**Most people think they need to learn the right programming language … but what you really need is to learn how to solve problems with code!**

Programming languages come and go, but I want take a deep-dive into what it means to write code confidently, break-down problems, and collaborate with other software engineers.

I would love it if you would take 3 minutes to answer a couple of questions about your struggles learning to program.

I'd love to share an early preview of the course as we get closer to time!

Also when the course is released, anyone on the waitlist will get a special 50% early bird rate.

[Share your thoughts using this form](https://6yjql9rns9f.typeform.com/to/vXtf2B4v)
Reading JWT token claims without a library
Tags: python, jwt, web
Published: 2022-10-14 16:31:34

---
title: Reading JWT token claims without a library
published: true
date: 2022-10-14 13:49:00 UTC
tags: python,jwt,web
canonical_url: https://banach.net.pl/posts/2022/reading-jwt-token-claims-without-a-library/
---

Almost everybody who works on web apps knows what JWT (JSON Web Token) is. They become pretty popular and are now widely used.

Without going into details (which can be read e.g. at [jwt.io/introduction](https://jwt.io/introduction)) JWT is built from three parts divided by dots:

```
header.payload.signature
```

The middle part, payload, is interesting for us. It contains claims, which are statements about an entity (e.g. the user) and some additional data.

For purpose of this post we will use an example token from [jwt.io](https://jwt.io/#debugger-io?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c) (click on the link to open it in the debugger!) which looks like this:

```
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

```

The payload in the token is just a [base64](https://en.wikipedia.org/wiki/Base64) encoded JSON object. That means we can decode it and load this JSON string into the dictionary to have easy access to properties.

There is only one tricky part here - base64 padding! The payload in the JWT is alfa-numeric only, there is no `=` character. To be sure that it will be decoded properly we need to add max padding (`==`) to the payload string - it will be ignored if not needed. But if we will not have it there (but it is expected to be) - decoder will throw an error.

To sum up all above stuff in simple lines of code in Python:

```python
import base64
import json
# Assuming the token is in the token variable 
token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9." \
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ." \
"SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
# Split by dot and get middle, payload, part;
token_payload = token.split(".")[1]
# Payload is base64 encoded, let's decode it to plain string
# To make sure decoding will always work - we're adding max padding ("==")
# to payload - it will be ignored if not needed.
token_payload_decoded = str(base64.b64decode(token_payload + "=="), "utf-8")
# Payload is JSON - we can load it to dict for easy access
payload = json.loads(token_payload_decoded)
# And now we can access its' elements - e.g. name
name = payload["name"]
# Let's print it - it should show "John Doe"
print(name)

```

You can run it in the browser on Replit ([Reading JWT token without library on Replit](https://replit.com/@elwin013/Reading-JWT-token-without-a-library#main.py)) or locally with Python 3.

And that’s all. It is pretty simple, isn’t it?

And it feels great to be able to do it without any additional tools! :-)
Day24 of #100DaysOfCode - Website Live!!!
Tags: webdev, nextjs, 100daysofcode
Published: 2022-10-14 13:46:24

My first website that I code from scratch is now online!

Go check it out at [hashing.energy](hashing.energy)!!

🥳 I’m so happy I’m not gonna code anything today, lol. Just gonna savor this moment. 🥰

Update: Now that the website is online, I noticed there are a few things I need to fix (one of them being the collapsed hamburger menu 😅).  But I’m still super happy! Will fix it tomorrow 🥰