teleren/devto huggingface dataset:
Redux toolkit : simplified
Tags: redux, reduxtoolkit, react
Published: 2023-04-18 12:26:59

**Definition**
Redux is a predictable state management library. It basically allows you to store JS variables in a global object that can be accessed and modified from any JS file (or component). 

You can use redux with vanilla JS or any JS framework like React, Angular, Vue, NextJS, etc. In this article, I have used redux-toolkit with react but the core concepts remain the same.

**Redux -> Redux toolkit?**
Redux is probably the most hated tool since it requires you to write a lot of boiler code to set up redux in your react app. To fix this redux team came up with a modern approach to redux called the redux toolkit. The redux toolkit is the recommended way to use redux. This new way of writing redux is clean and provides additional features. This article will help you understand the data flow in react with redux-toolkit (redux) and integrate redux in your app easily. 


**What are the benefits of having a state management tool?**
1. Makes the application predictable.
2. Solve the issue of prop drilling.
3. Makes the state flow easy to test and debug.
4. Most importantly, a good understanding of redux is a must if you wish to clear any frontend interview. 


**Three core concepts of redux:**
**1. action creator:** a function that returns an object that has at least one property called "type" and an optional property called payload. For example:

```
function add(){
   return{
     type: "ADD",
     payload: 2
   }
}
```

**2. store:**

The state of your entire application is stored in one big object called the store. Simply, it keeps all the variables and their values that is being used by multiple components. 


**3. reducer: ** 

Reducers are pure function that takes "previous state" and "actions" as parameter and it update the store based on the action type.

```
const reducer = (state = 0, action) => {

if (action.type == "ADD") {

return state + 1;

}

else(action.type == "SUBTRACT"){
  retrun state -1;
}
```




**React-Redux:**
Redux is not specially design for any particular framwork, it work with all the JS framwork. To use redux in a react app, we use react-redux liberary which is an official binding app. 

The only way to update the state is triggering an action. To trigger an action we use useDispatch() method provided by react-redux.



**Redux installation way:**







**Let revisit the key takeaways:**

whenever we want to update any value in the store, we dispatch the respective action. 

Based on the dispatched action type, reducer update the state. Reducer perform a deep copy of previous state to avoid overwriting the other properties of original state.

Every time state update, it re-render the components that are using that property? or the entire application? or only the component that is having useSelector?

For middlewares, redux provide applyMiddlewares?
Migrating your Heroku app to Railway
Tags: hosting, railway, webdev, tutorial
Published: 2023-04-18 12:24:46

**UPDATE August 2023**

Railway have recently removed their free tier, and now provide a hobby tier for $5 a month

---

Last November Heroku removed their free hobby tier, which left a lot of people looking for an alternative to host their apps with backends for free. 

I was recently recommended the Railway.app as an alternative to Heroku thanks to Claire Hardmans recommendation on the Codú discord. 

Railway's website states:

> "Bring your code, we'll handle the rest. Made for any language, for projects big and small. Railway is the cloud that takes the complexity out of shipping software."

### What does Railway offer? 

Railway provides a starter tier, which allows user to trial the platform without providing a credit card. This level gives users 512mb of RAM and a shared PCU/container and 1gb of disk space. Users are provided $5 of free credit/500 hours of usage, and deployments will shut off once the limit is reached (so no sneaky bills)

They also provide a developer tier which can either be prepaid or usage-based, and this tier is still free if you stay below the $5 free credit.

So I thought I'd try it out and transfer over my apps from Heroku to Railway (spoiler: it's super simple and quick!)

### Migration Instructions

1. Create a Railway account and connect to your GitHub.

2. On the Railway site select: 
    
    `Create a new project`
    🔻
    `Deploy from a Github repo`
    Choose which repo you want to deploy
    🔻
    `Add variables`

3. Copy over all your variables from Heroku to Railway.

4. Once deployment is successful, you can find the domain address in the projects settings, or on your dashboard.

And thats it! It really is that simple 

I'd love to hear if you use Railway and what you think, or if you're using another service to host your projects that you think is even better - leave me a comment below 😊

### 🚝 Railway Resources

[Railway.app](https://railway.app/)

[Railway Pricing Tiers](https://railway.app/pricing)

[Railway Docs](https://docs.railway.app/)
Hiring: Full Stack Developer
Published: 2023-04-18 12:07:23

As a Full Stack Developer, you’ll become a valuable member of an innovative and fast-growing department, working in a truly Agile environment utilising cutting-edge technologies.

You will build products supporting our fraud management products that help our clients as well
as our internal departments to expand our ecosystem and make an impact on our
business on a daily basis.

Our team develops generic solutions front end and back end with high-quality as infrastructure
libs or services, hence we increase the velocity and quality for product-oriented teams.

We believe that developers should take full ownership of their work: from the initial feature
planning phase alongside Product and Design; choosing the right technologies, designing the
code and architecture; coding; PRing; and all the way to actual deployment in CI/CD
environment, as well as post-deployment monitoring. It is all your responsibility.

Whether you enjoy writing complex business logic in the backend, crafting the UI to look and
feel exactly the way you want it to, or tweaking the servers and infrastructure to perform well at
scale, we encourage you to get your hands dirty end-to-end. It’s up to you how much you get
your Stack Full.

Our Stack: React, Node.js, Scala, AWS, Kafka, Docker, Kubernetes, Postgres, Elasticsearch,
Aerospike, snowflakes, airflow. Grafana, argoCD and more

Qualifications
 B.Sc. in Computer Science or equivalent
 5+ years of experience in client-side coding
 3+ years of experience with React
 Familiar with Angular
 2+ years of proven experience in hands-on server-side (nodeJS preferred)
 Familiar with microservices architecture, k8s
 An autodidactic approach to software development
 Passion for writing clean, SOLID, and robust code
 A team player with strong communication skills, but also capable of working independently
error 1452: cannot add or update a child row: a foreign key constraint fails
Tags: tutorial, programming, database
Published: 2023-04-18 11:42:05

The error message "Error 1452: Cannot add or update a child row: a foreign key constraint fails" is a database error that occurs when attempting to insert or update a record in a child table that violates a foreign key constraint with its parent table.

Foreign keys are used in relational databases to establish relationships between tables, where a column in a child table refers to the primary key of a parent table. This constraint ensures that data in the child table is consistent with the data in the parent table, preventing the creation of orphaned records or inconsistent data.

This error typically occurs when trying to insert or update a record in the child table with a value that does not exist in the parent table's primary key column. It could also happen when attempting to delete a record from the parent table that is still referenced by records in the child table.

To resolve this error, you can take the following steps:

Verify that the values being inserted or updated in the child table's foreign key column exist in the parent table's primary key column.
Check for any inconsistencies in the data between the parent and child tables, such as orphaned records or missing values.
Make sure that any operations on the parent and child tables are performed in the correct order, such as inserting parent records before child records.
If deleting records, ensure that any references to the records being deleted are updated or removed from the child table before attempting to delete the parent records.
Double-check the foreign key constraints and ensure they are defined correctly, with the correct column references and data types.

If you are still encountering the error after following these steps, it may be necessary to consult with a database administrator or developer for further investigation and resolution.
Component Immutability and RequiredArray
Tags: component, angular, design
Published: 2023-04-18 11:41:29

While reading through component design, one of the recommended tip is to never mutate the input properties.

Let's look at the example below. (I am using Angular but same can apply to other frameworks)

```javascript
@Component({...})
class MyComponent {
    @Input() status: Status[];
    get sortedStatus() {
        return this.status.sort();
    }
}
```

Here sort is a mutable operation. This not only sort the array but also mutates the array. 

I have prepared the [stackblitz](https://angular-njd2pq.stackblitz.io/). Here we have status array of type string. It's passed down to child component. It's displayed both in parent and child component. In the child component I have a button Sort Array that basically sorts the `status` that is received via `@Input()`.


![Sort Array from child component sort array and it is reflected in parent component](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/pffw9gthsx1d1rlur2hi.gif)



Sort Array from child component sort array and it is reflected in parent component.

We can prevent this behavior by using the **ReadonlyArray**


![The perks of using ReadonlyArray](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mqgga4wnn22bh427i3io.png)


This interface strips away all the mutable operations like _push, pop, shift, unshift_ along with _sort_.
Resolvendo problemas no HackerRank: Festa de Chocolate
Tags: javascript, beginners, programming
Published: 2023-04-18 11:18:04

Olá, seja bem vindo a mais um Resolvendo problemas no HackerRank: No caso de hoje, iremos ajudar Brenno a conseguir o máximod de chocolates numa promoção da loja de doces. Vejamos mais informações com a explicação e sua resolução.

**Chocolate Feast -**

Brenno adora chocolates e vai para a loja com `N` dinheiro no bolso. O preço de cada chocolate é `C`. A loja oferece um desconto: para cada `M` embalagem que ele dá para a loja, ele ganha um chocolate grátis. Quantos chocolates Brenno consegue comer? Nosso objetivo é descobrir isso:

- Imprimir o número total de chocolates que ele pode comer.
- N, W e C(N= dinheiro Brenno, C= chocolate preço, M= Promoção(Free Choco))

Vejamos um exemplo:


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



O resultado do primeiro, segundo e terceiro caso serão:

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

Vejamos o código:

```
function chocolateFeast(n, c, m) {
    // Write your code here
  //N= money's Brenno, C= chocolate's price, M= Sale(Free Choco)
  let choco = Math.floor(n / c);
  let candy = Math.floor(n / c); 
     
  while(candy >= m){
    let bougth = (choco + Math.floor(candy / m)) - choco;
      choco = choco + Math.floor(candy / m);
      candy = candy % m + bougth;
       
        
    }
  return choco
}
```

No início do algoritmo, declaramos duas variáveis que farão a mesma coisa:choco e candy, receber o valor inteiro da divisão de `N`e `C`. Eles irão ter propósitos diferentes ao final.

Feito isso, criamos uma estrutura de repetição `while`, onde enquanto a variável candy for maior que `M` que representa o valor da promoção em loja. Declaramos dentro desta condição uma nova variável: `bougth` que irá receber `choco`(a divisão de N e C) + o valor inteiro da divisão de `candy/m` - choco. O mesmo fazemos com `choco`, e `candy` recebe o próprio valor e o resto de sua multiplicação por `M` + `bougth`. Finalizando, retornamos o resultadod e choco. Vejamos:

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

Assim, concluímos mais um _Resolvendo problemas no HackerRank:_ até a próxima.
Use REST API endpoint over SDK for OpenAI
Tags: ai, openai, api, javascript
Published: 2023-04-18 11:17:44

It is common for most projects to use only one method from the [OpenAI JavaScript SDK](https://www.npmjs.com/package/openai)’s implementation, so why not use native `fetch` for the this one REST endpoint instead?

**Question?**

> In AI web projects or any web [AI template](https://www.vercel.ai/), if you want to access OpenAI API, why are you using `openai` npm module rather than the REST API endpoints directly?

I personally think **using REST endpoints** is the best possible approach in terms of runtimes compatibility.


![Using direct REST API endpoint instead of OpenAI SDK](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ka8ir96zmg6wqzbe6uek.jpeg)


For JavaScript AI projects the default recommendation should be to use native fetch and move to SDK later if necessary.


**Performance benefits are clear:**

- Reduced bundle size
- Using native fetch for compatibility with any runtime (edge, workers, deno, browser)
- streaming

```javascript
  const res = await fetch('https://api.openai.com/v1/chat/completions', {
    headers: requestHeaders,
    method: 'POST',
    body: JSON.stringify(payload),
  })
```

---

If you are running **long-running AI calls**, remember to use Edge Functions instead of Serverless Functions:

{% embed https://twitter.com/dom_sipowicz/status/1643732246107488258?s=20 %}
---

**References**:
- [Vercel Chat bot example using native fetch](https://vercel.com/templates/next.js/ai-gpt3-chatbot)
- [link to code snippet example](https://github.com/vercel/examples/blob/main/solutions/ai-chatgpt/utils/OpenAIStream.ts#L43-L47)


---

Godspeed

PS. Follow me on Twitter or LinkedIn
[https://twitter.com/dom_sipowicz](https://twitter.com/dom_sipowicz)
[https://www.linkedin.com/in/dominiksipowicz/](https://www.linkedin.com/in/dominiksipowicz/)
Introducing Deepgram Starter Apps
Tags: news, ai, python, deepgram
Published: 2023-04-18 11:15:06

---
title: Introducing Deepgram Starter Apps
published: true
description: Deepgram's Starter apps provide all users with a seamless and efficient onboarding experience.
tags: news, ai, python, deepgram
canonical_url: https://blog.deepgram.com/introducing-the-deepgram-starter-apps/
cover_image: https://a-us.storyblok.com/f/1001320/2400x1260/18ff9b97dd/2304-introducing-starter-apps-blog-2x.png/m/1200x0
---

Deepgram aims to make world-class language AI available to any developer through just an API call. With today’s launch of Deepgram Starter Apps, it’s even easier to start building applications which take real-time and prerecorded audio data and transform them into transcripts enriched with natural language understanding metadata.

Put simply, we help developers build quickly because we’ve already taken care of integrating Deepgram into Starter Apps. Whether you've been coding for decades or just passed CS50, Deepgram's Starter apps provide all users with a seamless and efficient onboarding experience.

### JavaScript Starter

The JavaScript Starter is the first arrival from the collection and provides developers with a pre-built Deepgram integration on Node.js, with a React frontend, to quickly get started with the Deepgram platform. With the JavaScript Starter, all developers can rapidly explore what Deepgram's platform can do.

Check out our [JavaScript Starter Apps on Github](https://github.com/deepgram-starters/deepgram-javascript-starters).

### Python Starter

The Python Starter is our follow up to the collection and provides developers with a pre-built Flask integration with Deepgram. Presently, there is a static frontend to interact with the Flask server.

Check out our [Python Starter Apps on Github](https://github.com/deepgram-starters/deepgram-python-starters).

## New transcription models included

Deepgram introduces two new models this week. These are available to try out immediately in our new Starter applications.

### Deepgram Nova

On April 13th, 2023, we announced Deepgram Nova, a cutting-edge Automatic Speech Recognition (ASR) system. Deepgram Nova achieves unprecedented performance, beating competitors in speed, accuracy, and efficiency.

### Whisper Cloud

Alongside Deepgram Nova’s release, we announced Deepgram Whisper Cloud. Following last month's release of OpenAI's Whisper API, we noticed its popularity, despite its limitations. We've developed our own fully managed Whisper API to address those limitations.

Read more about our [Deepgram Nova and Deepgram Whisper Cloud release here](https://blog.deepgram.com/nova-speech-to-text-whisper-api/).

## Read more

Read more about our new opensource projects in our latest post, [Introducing Deepgram Starter Apps](https://blog.deepgram.com/introducing-the-deepgram-starter-apps/).
React useState and useEffect hooks explained in simple term with example
Tags: webdev, react, hooks, programming
Published: 2023-04-18 11:02:25

React hooks were introduced in React version 16.8. The main purpose was to make functional components more useful .
Hooks allows us to change the state of react components (useState) or performing an after effect when changes occur in component state without the need of class component.

**RULES of react hooks,**

1.React hooks can only be used in react functions.
2.React hooks must be called at the top level.


**useState in hook in react :**

_First what is state in react?_

- A built in react object
- Can be used to store data about components.
- States are mutable, meaning their value can change

The useState() hook allows us to have state variables in the React functional component. It takes one argument which is the initial state and returns a state value and a function to update it.

``` js
const [count, setCount] = useState(0)
const increaseCount = () =>{
    setCount(count + 1)
};
```

**5 common usage of useState() ,**
1. Counter
2. State management.
3. Conditional rendering.
4. Toggler (ON/OFF,True/False)
5. Store api.

**useEffect in hook in react :**

_What are side effects in react?_

- Actions which are performed with the outside world
- Unpredictable because it can depend upon various things outside of react scope.

useEffect() hook accepts 2 arguments:
``` js
    useEffect(callback[, dependencies]);
``` 

Callback is a function that contains the side-effect logic. callback is executed right after the DOM update.
dependencies is an optional array of dependencies. useEffect() executes callback only if the dependencies have changed between renderings.

``` js
  useEffect(() => {
    setTimeout(() => {
    setCount((count) => count + 1);
   }, 1000);
  return function cleanup() {
    // Side-effect cleanup...
   };
},[dependencies]);
```


**Common usage of useEffect() ,**

1. Making request to an api for data
2. Performs asynchronous tasks  
3. To interact with browser api to manipulate DOM directly.
4. Reading data from local storage

What is the use Effect cleanup function?

- The useEffect cleanup allows us to tidy up our code before our component unmounts.

- When our code runs and reruns for every render, useEffect also cleans up after itself using the cleanup function.

- The cleanup function prevents memory leaks and removes some unnecessary and unwanted behaviors.
React - Manage many state updates
Published: 2023-04-18 11:00:22

Managing multiple states can rapidly become a complex task. 

In effect, it can create some synchronous problems. Let’s say you have this component:

```javascript
const MyComponent = () => {
	const [users, setUsers] = useState<User[]>([]);
	const [loading, setLoading] = useState<boolean>(false);
	
	const handleClick = () => {
    setLoading(true);

    someMethod()
			.then((newUsers) => {
	      setUsers(newUsers);
	      setLoading(false);
	    });
  };

	return loading ? (<Loader />) : (<button onClick={handleClick}>Update</button>);
};
```

The code is currently working. However, as it becomes more complex and has more states, you may encounter issues with its values and component refreshing.

To avoid this kind of behavior, you can store all your data in the same object.

```javascript
const MyComponent = () => {
	const [object, setObject] = useState({
		loading: false,
		users: []
	});
	
	const handleClick = () => {
    setObject({...object, loading: true});

    someMethod()
			.then((newUsers) => {
	      setObject({...object, users: newUsers, loading: false});
	    });
  };

	return loading ? (<Loader />) : (<button onClick={handleClick}>Update</button>);
};
```

In this case, that's totally fine because our object is pretty simple. However, if we have to deal with more states, it's better to use a reducer to externalize the object updates.

```javascript
const reducer = (state, action) => {
	switch(action.type) {
		case "start":
				return {...state, loading: true}
		case "end":
				return {...state, users: action.newUsers, loading: false}
	}
}

const App = () => {
	const [object, dispatch] = useReducer(reducer, {
		loading: false,
		users: []
	});
	
	const handleClick = () => {
    dispatch({type: "start"});
    someMethod()
			.then((newUsers) => {
		    dispatch({type: "end", newUsers});
	    });
  };

	return object.loading ? 
		(<Loader />) : 
		(<div><button onClick={handleClick}>Update</button></div>);
		
};
```

Now you can be sure that all your states will be synchronized, and you have total control over them.