teleren/devto huggingface dataset:
Axios interceptors For ReactJs
Tags: react, frontend, axios, javascript
Published: 2023-05-22 14:53:03

Interceptors allow you to modify the request or response before it is sent or received by the server. Interceptors are useful because they allow developers to add custom functionality to requests and responses without modifying the actual code that makes the request.

Install Axios in your Next.js project. Open your project directory in the terminal and run the following command

`npm install axios`

Create a new file (e.g., axiosInstance.js) to configure your Axios instance and define your interceptors

```
import axios from 'axios';
const axiosInstance = axios.create({
  baseURL: 'http://api.example.com', // Replace with your API base URL
});

// Request interceptor
axiosInstance.interceptors.request.use(
  (config) => {
    // Modify the request config here (add headers, authentication tokens)
		const accessToken = JSON.parse(localStorage.getItem("token"));

    // If token is present add it to request's Authorization Header
    if (accessToken) {
      if (config.headers) config.headers.token = accessToken;
    }
    return config;
  },
  (error) => {
    // Handle request errors here

    return Promise.reject(error);
  }
);

// Response interceptor
axiosInstance.interceptors.response.use(
  (response) => {
    // Modify the response data here
    return response;
  },
  (error) => {
    // Handle response errors here

    return Promise.reject(error);
  }
);

export default axiosInstance;
```

In the above code, we create an Axios instance using **`axios.create`** and set the **`baseURL`** to your API's base URL. You can modify this according to your API configuration.

The **`interceptors.request.use`** function is used to intercept and modify outgoing requests. You can add headers, authentication tokens, or perform other modifications to the request configuration.

The **`interceptors.response.use`** function is used to intercept and modify incoming responses. You can parse, transform, or handle errors in the response.

Now, you can use the axiosInstance in your components to make API requests with the configured interceptors. For example, in your component file (example.js)

```
import axiosInstance from '../axios/axiosInstance';

function ExamplePage() {
  const fetchData = async () => {
    try {
      const response = await axiosInstance.get('/api/data'); // Replace with your API endpoint

      // Handle the response data here
      console.log(response.data);
    } catch (error) {
      // Handle the error here
      console.error(error);
    }
  };

  return (
    <div>
      <h1>Example Page</h1>
      <button onClick={fetchData}>Fetch Data</button>
    </div>
  );
}

export default ExamplePage;
```
In the above code, we import the **`axiosInstance`** we defined earlier and use it to make API requests. You can replace **`/api/data`** with the appropriate endpoint URL for your API.

By using **`axiosInstance`**, the requests made from your project components will automatically go through the defined interceptors, allowing you to modify the requests and responses as needed.
Server Side Rendering (SSR) Vs Static Site Generation (SSG)
Tags: javascript, beginners, nextjs, webdev
Published: 2023-05-22 14:40:31

**Server Side Rendering (SSR)** and **Static Site Generation (SSG)** are terms used to describe how web pages are generated and rendered. This article explains the difference between both terminologies and when best to use each one.

## Server Side Rendering 
SSR refers to when a webpage is generated each time a user requests it. In other words, a page returned to the user at request time is a server-side rendered webpage.

![Server Side Rendering (SSR) description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/egfotv23c1w85nblc2tz.png)

Nextjs provides the [getServerSideProps](https://nextjs.org/docs/pages/building-your-application/data-fetching/get-server-side-props) method to make it easy to do SSR out of the box.

### When is the best time to use SSR?
- SSR is best when rendering complex pages with dynamic contents such as authentication data.

- It is also the best when it comes to SEO.

## Static Site Generation (SSG)
SSG is a method used to generate webpages at build time. The pages are then re-used each time a user requests them.

![Static Site Generation (SSG) description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e91k4tg2r79otd2h6sv7.png)

The [getStaticProps](https://nextjs.org/docs/pages/building-your-application/rendering/static-site-generation) method is used for SSG in Nextjs.

### When is the best time to use SSG?
- The best time to use SSG is when a webpage has less dynamic data. For example, a blog post page.

- SSG provides better load time since the pages are already generated.

## Summary
The image below outlines the difference between SSR and SSG:

![Difference between SSR and SSG description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fhx3lgv0ym97spgdim6k.png)

## Conclusion
The article aimed to clarify the difference between SSR and SSG.

It defined each concept and provided the best cases for all of them. It also introduced you to the Nextjs methods for handling SSR and SSG.

I encourage you to look more into the [documentation](https://nextjs.org/docs) and explore code samples and other use cases.
Installing and using multiple PHP versions with Debian/Ubuntu
Tags: php, ubuntu, linux, tutorial
Published: 2023-05-22 14:32:51

Ever wondered if there is a [nvm](https://github.com/nvm-sh/nvm)-like for PHP?

Not exactly, but we can have multiple PHP versions in our system and switch between them easily, let's see.

## Installing multiple versions

The default apt repository only have one PHP version availbale, usually the last stable version. To install others we have to add Ondřej's repository.

```bash
sudo apt install software-properties-common
sudo add-apt-repository ppa:ondrej/php
sudo apt update
```

We can now install individual versions.

### PHP 7.4

```bash
# add any other extension you may need
sudo apt install -y php7.4-cli php7.4-common php7.4-mysql php7.4-zip php7.4-mbstring php7.4-curl php7.4-xml php7.4-bcmath php8.1-sqlite3
```

### PHP 8.1

```bash
# add any other extension you may need
sudo apt install -y php8.1-cli php8.1-common php8.1-mysql php8.1-zip php8.1-mbstring php8.1-curl php8.1-xml php8.1-bcmath php8.1-sqlite3
```

## Switching between versions

Now use the following command to switch between versions.

```bash
sudo update-alternatives --config php
```

## Other distros

- Fedora also has a similar command: [alternatives](https://www.redhat.com/sysadmin/alternatives-command).
A Brief History of the Internet and HTTP Protocol
Published: 2023-05-22 14:29:00

Javascript wins out in my opinion, find out how below

Now and again we need reminders about our rich beginnings
   Topics…. software architecting - request and response objects  - the client server model - http
      Origins of request and response objects - Major Milestones

**1965** Donald Davies developed the concept of packet switching
http://www.nethistory.info/History%20of%20the%20Internet/beginnings.html#:~:text=In%201965%2C%20before%20Arpanet%20came,the%20NPL%20Data%20Communications%20Network.
**1969** ARPANET the first public packet-switched computer network
**1970s** NCP preceded TCP - network control protocol used in arpanet
**1975** Bill Gates starts Microsoft
**1979** Compuserve dial up service launched - original online portal for the general public with news, weather, chats and email
**1983** TCP/IP replaced NCP
**1991** world wide web coined
**1993** first version of HTML
**1993** Mosaic - first web browser, then became netscape
**1995** java released - also rise of javascript for netscape2, (the first ECMA standard)
**1995** MySQL first appeared - open source vs proprietary Oracle db
**1996** first mobile phone with internet connectivity - The Nokia 9000 Communicator
**1998** java servlet api - also jsp - doGet doPost became servlet service method
                   This is why java was so prominent at the time - popularized server side computing
                   JSP was for the frontend
**1998** soap api
**2000** rest api - rise of the http network -> crud awareness - get, post, put
                          https://en.wikipedia.org/wiki/Representational_state_transfer re roy fielding
**2006** jquery ajax - refreshed only part of page - div structure -turned networking upside down
                                                                                Probably the most important milestone
         \<div id=”result”> only the content in this div refreshes/reloads \<div>
**2015** fetch api - genericized the ajax process - plain javascript now mainstream (ECMAScript 6)
**2021** why is jquery still dominant - 58% of websites still use it
            https://thenewstack.io/why-outdated-jquery-is-still-the-dominant-javascript-library/
**2023** everything can be done in plain javascript these days, react just complicates matters by adding extra overhead, node.js does the same whereas plain javascript simplifies both, also no need for java or servers anymore, just do it all on the front end which now executes the http request
**2023** age of serverless computing, cdn and edge network

**Afterthoughts**

1995 was a pivotal year - when both frontend and backend collided
            But looks like frontend prevailed and won by 2023 

Thoughts on Ditching JQuery in favor of Plain Vanilla Javascript
    1 it requires a slow loading external library = unnecessary overhead
    2 it has security issues
    3 why use a whole library when u are only using a couple of its components
Also ditch Node, no need for all those dependencies when ECMA has solved them all
    4 Fetch API replaced jquery ajax back in 2015
Generic algorithms on top of redb database
Tags: help, rust, database
Published: 2023-05-22 14:23:48

Hi, I need help with implementing some generic algorithms in rust on top of redb database tables.

I have a redb database with 2 tables (but there will be more) and I need to be able to use the same algorithms on all tables.

Each redb table has wrapper struct implemented - NodeTable and FWUStateTable. To allow generic programming of the algorithms, I declared a few traits - TableOps, DatabaseTable, TableKey - and tried to implement the algorithms as TableOps functions.

But after 3 days, I still can't get generic types and lifetimes right, there is simply too much of them and they don't play together.

Subjectively there is also too many bounds defined on trait TableOps, and I suspect I do something totally wrong.

Could someone look at the repo here:

https://github.com/elrafoon/ptnet-mgr/tree/master/ptnet-mgrd/src/database

and give me some advice?

I'm a quite new to rust....

Thanks!
You can't out-market a bad product to grow.
Published: 2023-05-25 07:24:37

---
title: You can't out-market a bad product to grow.
published: true
date: 2023-05-22 14:19:28 UTC
tags: 
canonical_url: https://blog.afrieirham.com/you-cant-out-market-a-bad-product-to-grow
---

When thinking about marketing your product you need to make sure what you're selling is valuable. Your product needs to actually deliver its promises.

I am currently thinking of a way to better market one of my product, CariKabel.com, and the best way to do marketing is to show proof that your product do indeed helps people achieve their goals.

But CariKabel has yet to have any success stories that I can use for my marketing.

That is when I realized I'm not comfortable just selling a "dream".

A dream is what it _can_ do vs what it _has_ achieved it's not tangible.

* * *

Yes, you could get sales selling a bad product and have some "success", but I don't think it's sustainable.

You probably should be thinking about your product's impact on your customers if you want a sustainable business.

CariKabel's main goal is to help job seekers have a better job-hunting experience vs the traditional way by giving you access to the referrer's email of the people in the company that you're interested in.

For example, if you want to work for Hashnode.

You would probably have a higher chance of getting called for an interview being referred by someone working there vs applying directly through their job portal.

At least that's the idea that's CariKabel's "dream".

But until I can prove that is what's happening, it's really hard for me to spend more time and money marketing it without any success stories.

Plus I'll feel a lot better selling stuff that helps people. I won't be thinking about weird marketing tactics to get customers to compensate for a bad product.

However, you can't get any success stories without customers. So you'll still need marketing to start.

But after getting your first few customers, the next step is to get testimonies.

Then you can think about scaling.

I mean it makes more sense that way:

1. Get the first few customers

2. See if they achieve what you're promising using your product

3. If yes, you can use their stories/testimonies to reach more people

4. If not then maybe your product does not make sense, or you need to change something about it

So yeah, that is why I said you can't out-market a bad product. You'll eventually fail even if it seems you're doing great (i.e. sales are high in the beginning).
Tartigraid - progress update
Published: 2023-05-22 14:18:12

Another progress update!

Today I created the first version of the request page.
Here you can see all the past invocations of an http request made to you api.

Here is a preview:

Click on the desired request here:
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9sgm4gi9l4933igcy4vt.png)

See all the invocations for this request
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/gyl7jb9kamtpjhtfck65.png)

AND THE BEST THING ABOUT THIS FEATURE:

You can re-execute specific invocations in order to easily develop you backend.

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

Upcoming features for this page include:
Automatic JSON schema/Typescript/Curl requests/OpenAPI schema generation.
You will be able to easily generate schemas and types for your http request.

Let me know in the comments if you would love to see some code/architecture blog posts.
Python: prevent import errors
Tags: python, beginners, programming
Published: 2023-05-22 14:04:33

I've already asserted in this series that you should catch errors in your Python scripts.

Not only that it improves user experience, but it may save you some precious time if you provide support.

## What are imports?

Imports can simply consist of calling a third-party package in your script to speed up development or avoid reinventing the wheel.

It's usually done this way in Python:

```Python
import my_awesome_package
```

But you can also alias it:

```Python
import my_awesome_package as another_name
```

When you start sharing your code, you need to tell people how to install all dependencies to prevent bad import errors.

Indeed, if "my_awesome_package" is a third-party package that is not pre-installed with Python, users will get a fatal error.

Fortunately, Python has its own package manager [Pip](https://pypi.org/project/pip/) that comes with Python, so Python devs usually put a file called `requirements.txt` at the root of their projects to indicate third-party modules to install.

Then, users only have to use the following command:

```
pip install -r requirements.txt
```

## Devs are lazy, so are users

We all know that we must read the _Fabulous_ documentation (RTFM), but, in practice, it's often skipped.

Whether it's good or bad (mostly bad) is not our problem here. People just do that.

However, you can add some extra check:

```Python
import sys

try:
    import my_awesome_package
except ModuleNotFoundError:
    print("Please run 'pip install -r requirements.txt' to use this script.")
    sys.exit(1)
```

While it's not an official recommendation from the documentation, I like to include such checking.

## Wrap up

Catching import errors can be beneficial even if it adds a few lines in your script.
Python's BigQuery External CVS tables and null_marker challenge
Tags: bigquery, python, externaltables
Published: 2023-05-22 13:38:03

Testing data pipelines is crucial for ensuring their efficiency and reliability. When dealing with data sources like BigQuery external tables, it becomes necessary to emulate these data sources to perform thorough pipeline testing.

So idea is to create external CSV table using Python's BigQuery library.

For additional context, we treat empty value as "" and `null` as `\N`.

Unfortunately, this library does not allow you to specify `null_marker` for CSV files while creating an external CSV table using [`ExternalConfig`](https://cloud.google.com/python/docs/reference/bigquery/latest/google.cloud.bigquery.external_config.ExternalConfig)

The `null_marker` option is not presented in [`CsvOptions`](https://cloud.google.com/bigquery/docs/reference/rest/v2/tables#CsvOptions), in contrast to, for example, `skip_leading_rows`.

```python
external_config = ExternalConfig(ExternalSourceFormat.CSV)
external_config.options.skip_leading_rows = 1
external_config.options.null_marker = '\\N' # does not work
```

Simultaneously, it's important to note that while a Data Definition Language (DDL) statement that includes the `null_marker` option may work successfully when executed directly in the BigQuery console, it might not function as expected when submitted using the Python client.

```sql
CREATE
OR REPLACE EXTERNAL TABLE project_name.dataset_name.table_name (
    `field1` STRING,
    `field2` STRING,
) OPTIONS (
    uris = ['gs://bucket_name/prefix_name/file_name.csv'],
    format = CSV,
    skip_leading_rows = 1,
    null_marker = '\\N'
)
```

If you execute this query in the BigQuery console, your table will be created successfully and ready for querying. However, if you attempt to submit the same query using the Python library, you will encounter the following exception:

```python
>>> bq_client.query(query=create_table_ddl).result()
google.api_core.exceptions.BadRequest: 400 Syntax error: Illegal escape sequence: \N
```

Even when attempting to shield the `\\\\N` sequence, it may not produce the expected outcome. The actual null values are not processed as intended; instead, they remain as `\\N` rather than being interpreted as null.

If you have insights or solutions regarding the challenge of handling null values in emulated tables, kindly share them in the comments section. This will help improve the guide and provide a comprehensive solution for others facing a similar issue.
🎉🎂 Atenção a todos! É semana do meu aniversário e estou muito animado! 🎉🎂
Tags: video, youtube, conteudo, webdev
Published: 2023-05-22 14:04:02

Quero convidar cada um de vocês para celebrar comigo e conhecer o meu canal no YouTube. É o lugar onde compartilho conteúdos incríveis sobre desenvolvimento de software e tecnologia. Você não vai querer perder!

🎥 YouTube: https://www.youtube.com/@hdevinfo

No meu canal, você encontrará vídeos divertidos, tutoriais práticos e dicas valiosas para aprimorar suas habilidades de programação. Vamos explorar juntos o mundo da tecnologia!

📢 Então, se você é apaixonado por desenvolvimento de software, curioso sobre as últimas tendências tecnológicas ou simplesmente adora aprender coisas novas, inscreva-se no meu canal. Tenho certeza de que você encontrará conteúdo interessante e inspirador!

🌟 Não se esqueça: meu aniversário é nesta sexta-feira, dia 26/05! É uma semana especial, cheia de novidades e surpresas. Vamos comemorar juntos!

🎁 Ah, e para deixar tudo ainda mais especial, estou preparando alguns presentes exclusivos para os inscritos do canal. Então não perca tempo, inscreva-se agora e garanta seu lugar nessa festa!

✨ Espero ver vocês por lá! Vamos compartilhar conhecimento, trocar experiências e construir uma comunidade incrível de desenvolvedores.

#Aniversário #DesenvolvimentoDeSoftware #Tecnologia #Inovação #YouTube #HDevInfo

Robson Mendonça
Exploring React Routes 🚀
Tags: webdev, react, programming, beginners
Published: 2023-05-22 14:03:08

**📍 What are React Routes?**

- React Routes are a fundamental part of building single-page applications (SPAs) with React.
- They enable seamless navigation within a web application, allowing users to move between different pages or views without the need for a full page refresh.
- React Routes leverage the concept of declarative routing, meaning that you define the desired behavior of your routes in a straightforward and intuitive manner
.
**🛠️ Setting Up React Routes:**

**Copy code
npm install react-router-dom**

**Import and Wrap the App**: 

- Import the necessary components from React Router and wrap your application with the Router component.

**Define Routes:**
 - Set up your routes using the Route component, specifying the desired path and corresponding component to render.

**🔑 Key Concepts:**

**Route Matching:**

- React Router matches routes based on the provided path and renders the corresponding component when the path is matched.
- You can define exact matches, parameterized routes, and even handle dynamic segments in your paths.

**Nested Routes:**

- React Router supports nested routes, allowing you to create hierarchical structures for more complex applications.
- Nesting routes helps you organize your code and define specific routes for different sections of your application.

**Route Parameters**:

- Route parameters allow you to extract dynamic values from the URL and pass them as props to your components.
- By utilizing route parameters, you can create dynamic and interactive routes, making your application more powerful and personalized.

**Programmatic Navigation:**

- React Router provides methods and hooks for programmatic navigation, enabling you to navigate to different routes programmatically.
- These features are handy when handling form submissions, user authentication, or any scenario requiring conditional navigation.