teleren/devto huggingface dataset:
【Next.js, GraphQL, Apollo Client】How to rewrite Apollo Client cache after a mutation. -part1-
Tags: nextjs, cache, apolloclient, graphql
Published: 2024-03-14 00:40:15

In this article, I'm going to share how I update the my app UI after a mutation by providing an upload function to useMutation.

I am right now developing an application using **GraphQL** and **Apollo Client**, which has form where user can register their favourite piece of clothes. 
After a successful register, user will be navigated to a 'wardrobe' page, where all the registered pieces are displayed.

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

wardrobe page↓

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

But If I just implement register piece function using useMutation, like below,  **users won't see the piece that they just registered** unless they reload the page.

```javascript
 const [registerPiece] = useMutation<RegisterPieceMutationData>(REGISTER_PIECE_MUTATION);
```

This is because it doesn't refetch all the pieces of clothes data every time users visit the wardrobe page. **It obtains the data from Apollo Client cache** that is stored the last time it fetched the data from GraphQL server.

So I need to **rewrite the cache** every time user registered the piece. But How?

**Using Refetch Query?**
There are several ways to rewrite the cache. 
The easiest way is to use `refetchQueries`.

```javascript
const [addTodo, { data, loading, error }] = useMutation(ADD_TODO, {
  refetchQueries: [
    GET_POST, 
  ],
});
```
The code above is from the [Apollo Client official documentation](https://www.apollographql.com/docs/react/data/mutations/#include-modified-objects-in-mutation-responses).
As shown in code above, you can put **refetchQueries array** in mutation's option.
This enable app to refetch a `GET_POST` query after performing ADD_TODO mutation and that rewrite the cache as a result.

in My Case↓

```javascript
  const [registerPiece] = useMutation<RegisterPieceMutationData>(REGISTER_PIECE_MUTATION, {
    refetchQueries: [
      {
        query: GET_WARDROBE_QUERY, //refetch all the pieces data
      },
    ],
  });
```

While the use of a refetch query is straightforward and useful, it comes with the **downside of extra network requests**. This can result in suboptimal performance due to the increased load times and data usage.

So I decided to use update function instead, which I will explain in the part2.

Cover Photo Credit:
from <a href="https://unsplash.com/ja/%E5%86%99%E7%9C%9F/%E7%B7%91%E3%81%A8%E3%83%94%E3%83%B3%E3%82%AF%E3%81%AE%E3%83%97%E3%83%A9%E3%82%B9%E3%83%81%E3%83%83%E3%82%AF%E5%AE%B9%E5%99%A8-AEU9UZstCfs?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Unsplash</a>
taken by <a href="https://unsplash.com/ja/@elloproducts?utm_content=creditCopyText&utm_medium=referral&utm_source=unsplash">Ello</a>
La regla aspect-ratio: Una nueva forma de controlar la forma de tus elementos
Published: 2024-03-14 00:31:52

La regla aspect-ratio es una de las últimas novedades en CSS que te permite controlar la relación de aspecto de un elemento. Esto significa que puedes asegurarte de que tus elementos siempre se muestren con la forma correcta, independientemente del tamaño de la pantalla o del dispositivo en el que se vean.

**¿Qué ventajas ofrece?**

- Mayor control sobre la forma de tus elementos: Puedes mantener la forma original de tus imágenes, videos o cualquier otro elemento, sin importar el tamaño o la resolución de la pantalla.
- Mejora la experiencia del usuario: Tus diseños se verán más consistentes y profesionales en cualquier dispositivo.
- Reduce la necesidad de imágenes fijas: Puedes usar aspect-ratio para crear elementos con formas geométricas perfectas, como cuadrados, círculos o rectángulos, sin necesidad de utilizar imágenes.
- Facilita el diseño responsivo: Es una herramienta poderosa para crear diseños que se adapten a diferentes tamaños de pantalla sin perder la forma original de tus elementos.

**¿Qué mejoras trae consigo?**
- Solución más flexible que las unidades relativas: Antes, era necesario usar unidades relativas como % o vw para controlar la forma de los elementos. Sin embargo, esto podía resultar impreciso y difícil de controlar. aspect-ratio ofrece una solución más precisa y flexible.
- Soporte nativo en los navegadores modernos: La mayoría de los navegadores modernos ya tienen soporte nativo para aspect-ratio, lo que significa que no necesitas usar prefijos de proveedores.
Fácil de usar: La sintaxis de aspect-ratio es simple y fácil de entender.

Ejemplo de uso:

CSS

```
.imagen {

aspect-ratio: 16/9;

}
```



En este ejemplo, la imagen siempre se mostrará con una relación de aspecto de 16:9, independientemente del tamaño de la pantalla.

En resumen, la regla aspect-ratio es una herramienta poderosa que te permite controlar la forma de tus elementos de forma precisa y flexible. Es una gran mejora con respecto a las soluciones anteriores y te permite crear diseños más consistentes y profesionales en cualquier dispositivo.

**Recursos adicionales:**
CSS aspect-ratio: https://developer.mozilla.org/en-US/docs/Web/CSS/aspect-ratio
Building Interactive UIs with Vue.js
Tags: webdev, javascript, programming, beginners
Published: 2024-03-14 00:28:34

## Introduction

In today’s fast-paced digital world, creating a visually appealing and interactive user interface is essential for any successful website or application. This is where Vue.js comes into play. Vue.js is a progressive JavaScript framework that allows developers to easily build interactive user interfaces (UIs). In this article, we will explore the advantages, disadvantages, and features of building UIs with Vue.js.

## Advantages

One of the main advantages of using Vue.js for building UIs is its simplicity. It has a small learning curve, making it easy for developers to get started. Moreover, Vue.js is lightweight, and its virtual DOM (Document Object Model) efficiently updates the user interface, resulting in faster rendering and better performance. Additionally, Vue.js offers a component-based structure, making it easier to manage and reuse code.

## Disadvantages

Although Vue.js has many advantages, it also has some limitations. One of the biggest disadvantages is its lack of official support and documentation compared to other JavaScript frameworks like React and Angular. This makes it difficult for developers to find solutions to complex problems.

## Features

Vue.js has an extensive set of features that make it a popular choice among developers. It offers two-way data binding, which means any changes made in the user interface will reflect in the data, and vice versa. It also provides a built-in state management system, making it easier to manage and update application data. Moreover, Vue.js has a robust ecosystem, with a wide range of plugins and tools that developers can use to enhance their UIs.

### Code Example: Two-Way Data Binding in Vue.js

```vue
<template>
  <div>
    <input v-model="message" placeholder="Edit me">
    <p>The message is: {{ message }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      message: ''
    }
  }
}
</script>
```

This example demonstrates the simplicity of two-way data binding in Vue.js. The `v-model` directive is used to bind the input field to the `message` data property, enabling real-time updates between them.
## Conclusion

In conclusion, Vue.js is a powerful and efficient JavaScript framework that simplifies the process of building interactive UIs. While it has its limitations, its features and advantages make it a popular choice among developers. With Vue.js, you can create stunning and highly responsive user interfaces that will enhance the overall user experience. So, if you are looking to build dynamic and engaging UIs, Vue.js should definitely be on your radar.
What is a Relational Database for Beginners
Tags: webdev, beginners, sql, database
Published: 2024-03-14 00:23:00

So, let us take a look real quick at a relational database, as other people refer to it as a SQL database.


![Student table and users table](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/2n32mkoc08odqklludos.png)


Over here we have two examples of tables. So, this is how we would store information in a relational database.

So, over here I have a student table. And this student table might store individual students. So, you will see over here we have an id, a name and a major.

So, for every single one of my students, I have an entry just like this. And you will notice over here, I am giving each of these entries and ID. And that ID will uniquely identify that row in the table.

Then over here we have a users table. So, maybe you are creating users for your application. So, they have a username, a password and then an email.

So the username is something that is going to be unique. It is something that uniquely identifies each row in the table. And then, we are also storing the password and email.

So, we kind of talked about how relational databases store data in tables. And, when we want to create a relational database, we can use a relational database management system.

And a relational database management system, or a RDBMS is just a database management system that helps you create and maintain a relational database.

Some of the most popular are MySQL, Oracle, PostgeSQL, and MariaDB.

So, there are a bunch of these that are extremely popular. And relational database management systems use something called Structured Query Language or SQL.

And SQL is a standardized language for interracting with relational database management systems.

So remember, a relational database management system is just a software application that we can use in order to create, maintain and do different things to our relational database.

And SQL or Structured Query Language, is the language that we can use to interract with those relational database management systems.

So, we can use SQL to perform CRUD operations, as well as other administrative tasks like user management, security, backup etc.

And we can use SQL to define tables and structures. So a relational database uses tables in order to organize this information, and we can use SQL to define those tables then insert information into those tables.

And SQL is a standardized language which means it is pretty much used on every Relational Database Management System.

However different Relational Database Management Systems will implement SQL just a little bit differently. So, not all SQL code that you use on one relational database management system will pour over to another one without slight modification.

P.S. This is a small sneak preview of my flagship course, [The Art of Web Development](https://karlgusta.gumroad.com/l/mwiky/6wh7z13). 14 Chapters and 111 Lessons that will teach you how to build a web app and get a high-paying job (even if you're just starting or don't have an idea).

That's it. Happy Coding!
Repositório Mulheres na Tecnologia
Tags: wecoded, womenintech, braziliandevs, webdev
Published: 2024-03-14 00:11:15

Para celebrar o **we_coded** do @thepracticaldev venho compartilhar o repositório colaborativo **Mulheres na Tecnologia** que criei no GitHub para reunir conteúdos produzidos por mulheres referência na tecnologia e comunidades destinadas a pessoas que se identificam com o gênero feminino.

Criei o repositório com o objetivo de reunir conteúdos de referência para pessoas desenvolvedoras e promover visibilidade e espaço para conteúdos tech produzido por mulheres, comunidades, organizações e instituições, ao conhecer iniciativas e referências que me inspiraram como criadora de conteúdo no  [instagram.com/ana.tech.dev](https://www.instagram.com/ana.tech.dev/)

O repositório recebeu contribuições na Hacktoberfest 2022 e Hacktoberfest 2023 de contribuidoras que indicaram conteúdos como: comunidades, cursos, formações, eventos e podcasts. Muitos artigos do Dev Community (dev.to) foram indicados para o repositório.

## Repositório no GitHub
Acesse [Repositório Mulheres na Tecnologia](https://github.com/anatechdev/mulheres-na-tecnologia) em perfil de organização no GitHub e contribua para manter o conteúdo do repositório atualizado.

{% embed https://github.com/anatechdev/mulheres-na-tecnologia %}

> Por mais mulheres na tecnologia!

Ana Maria | Tech e Dev
[dev.to/anamaria](https://dev.to/anamaria)
[instagram.com/ana.tech.dev/](https://www.instagram.com/ana.tech.dev/)
[github.com/anamariasilva](https://github.com/anamariasilva)
10 reglas CSS que debes conocer para empezar en el desarrollo web
Published: 2024-03-13 23:52:13

¿Quieres dominar el arte de dar vida a tus diseños web? Entonces necesitas conocer las reglas CSS que son la base de cualquier proyecto web. Estas 10 reglas te darán una sólida base para comenzar tu viaje como desarrollador web.


**1. Selectores:**

Aprende a seleccionar los elementos HTML que deseas modificar con precisión. Domina los selectores por tipo, clase, ID, descendientes y adyacentes para tener un control total sobre tu diseño.

**2. Propiedades y valores:**

Explora la amplia gama de propiedades CSS que puedes usar para modificar la apariencia de tus elementos. Desde colores y tipografías hasta dimensiones y posicionamiento, descubre cómo dar forma a tu visión.

**3. Box Model:**

Comprende cómo se estructura el espacio alrededor de tus elementos con el modelo de caja. Domina las propiedades como margin, padding y border para crear diseños limpios y organizados.

**4. Posicionamiento:**

Ubica tus elementos con precisión en la página web utilizando diferentes métodos de posicionamiento. Desde static y relative hasta absolute y fixed, aprende a controlar la ubicación de cada elemento.

**5. Floats:**
Conoce cómo los elementos flotantes pueden ayudarte a crear diseños con columnas y alinear elementos de forma flexible. Domina las propiedades float y clear para lograr layouts adaptables.

**6. Flexbox:**
Despídete de los floats y descubre la flexibilidad de Flexbox. Crea layouts de una sola dimensión o multidimensionales con facilidad, utilizando propiedades como flex-direction y justify-content.

**7. Grid Layout:**

Organiza tus elementos en una estructura de cuadrícula bidimensional con Grid Layout. Define filas y columnas, y disfruta de un control preciso sobre la distribución de tu contenido.

**8. Media Queries:**

Adapta tus diseños a diferentes dispositivos y tamaños de pantalla utilizando media queries. Responde a las necesidades de cada usuario, desde smartphones hasta desktops, con un diseño flexible.

**9. Animaciones:**

Agrega dinamismo a tu sitio web con animaciones CSS. Crea transiciones suaves, efectos llamativos y experiencias interactivas que cautiven a tus usuarios.

**10. Transformaciones:**

Modifica la posición, tamaño y rotación de tus elementos con las transformaciones CSS. Crea efectos 3D, animaciones complejas y diseños más atractivos.

Con estas 10 reglas CSS como base, estarás listo para comenzar a crear sitios web increíbles. Recuerda que la práctica es la clave para dominar el arte del desarrollo web. ¡Empieza a experimentar y descubre todo el potencial que CSS tiene para ti!

**Recursos adicionales:**

CSS Tutorial: https://www.w3schools.com/css/default.asp
CSS Diner: https://flukeout.github.io/
CSS Grid Garden: https://cssgridgarden.com/

¡Feliz desarrollo web!
Nurturing Relationships for AI Excellence
Tags: podcast, codenewbie, career, beginners
Published: 2024-03-13 23:43:18

### Hey y'all!

If you are new here, hello and welcome! I am here today with CodeNewbie Podcast, where we come to you weekly with an interview with a tech professional, sharing supportive advice for newbies in tech. 

_What's not to like!_ 

![Someone shouting at a computer.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nxpvmqcicmy4oyvgojpj.gif)

---

Our first episode of **CodeNewbie Podcast Season 27** is out now with [Shawn Charles](https://twitter.com/ShawnBasquiat), Developer Advocate from [The Hunt](https://twitter.com/TheHuntSpaces).

Happy first day of Season 27! 🎉✨

Shawn tells us more about his journey into tech by maintaining websites for local businesses, what inspired him to do bootcamp, and his advice for finding a career in an AI-predominant job field.

Without further ado, if you would like to listen you can:

- [Listen on Apple Podcasts](https://podcasts.apple.com/us/podcast/codenewbie/id919219256?i=1000649083149)

- [Listen on Spotify](https://open.spotify.com/episode/4MEwHLaYWY5AgP1sZ1VEAh?si=66ad80974e0a40c2&nd=1&dlsi=77a6348b190b4d0e)

- Listen right here on DEV:

{% podcast https://dev.to/codenewbie/s27e1-nurturing-relationships-for-ai-excellence-shawn-charles %}

Or, listen wherever you normally get your podcasts.

![Cartoon person jamming to music saying, "It's a Hit!"](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/m1eg98x9rku16gxd9rvr.gif)


---

### We will see you next week for more of our _AI-themed_ Season of CodeNewbie Podcast.

If you are eager for more podcast-discussions, tune in over at [Podcast Palooza](https://dev.to/devteam/podcast-palooza-what-are-you-listening-to-interview-edition-3a8) on Mondays to share your favorite content!

Sincerely,
**Rachel from the DEV and CodeNewbie Teams**
(they/them)

---

_PS: **Holy heck.** We would love for you to review our podcast, drop a rating, drop a like, or whatever you can to show your support. It truly means a ton, we love to see your kind words, and we wouldn't be here without you!_
Heap
Tags: cpp, algorithms, beginners, learning
Published: 2024-03-13 23:41:55

Estructura de Datos

Se realizan pruebas de inserción y extracción de datos en un Heap. Primero se muestra el dato aleatorio a ingresar al heap, después el heap completo y por último la extracción ordenada de cada número del heap imprimiendo estado del heap en cada extracción.


***


Data Structure

Data insertion and extraction tests are performed in a Heap. First, the random data to be entered into the heap is shown, then the complete heap, and finally, the ordered extraction of each number from the heap, printing the heap status in each extraction.


***

main.cpp

```

#include <iostream>
#include "heap.hpp"

int main() {
  
  srand((unsigned) time(nullptr));

  int n = 100;

  heap m(n);

  for (int i = 0; i < 10; i++){

    int x = rand() % n + 1;

    cout << "Agregar " << x << ": ";

    m.ins(x);
    m.print();
  }

  cout << "\n\n";
  m.print();
  cout << "\n\n";
  for (int i = 0; i < 10; i++){

    cout << "Extraer " << m.tout() << ": ";

    m.print();
  }
  
}
//https://dev.to/imnotleo/heap-39no
```
***

heap.cpp

```

#include "heap.hpp"

  heap::heap(int c){

    n = c;
    s = 0;

    a = new int[n];
  }

  heap::~heap(){

    delete[] a;
  }

 void heap::ins(int x){

   assert(!full());

  a[s] = x;
  int i = s++;
   while (i > 0 && a[i] > a[parent(i)]) {
     int c = a[i];
     a[i] = a[parent(i)];
     a[parent(i)] = c;

     i = parent(i);
   }
   
 }

int heap::tout(){
  assert(!empty());

  int x = a[0];
  int i = 0;
  a[0] = a[--s];
  while (i <= parent(s-1) && a[i] < a[maxChild(i)]){

    int m = maxChild(i);
    int c = a[i];
    a[i] = a[m];
    a[m] = c;
    i = m;
  }

    return x;
}

int heap::maxChild(int i) {

  assert(i <= parent(s-1));

  if (right(i) > s) return left(i);
  if (a[left(i)] > a[right(i)]) { return left(i); }
  else return right(i);
  
}

void heap::print(){

  cout << "[ ";
  for (int i = 0; i < s; i++) cout << a[i] <<" ";
  cout << "]\n";
}
//https://dev.to/imnotleo/heap-39no
```

***

heap.hpp

```

#ifndef heap_hpp
#define heap_hpp

#include <stdio.h>
#include <iostream>
#include <cassert>
using namespace std;

class heap {

  int parent(int i) { return (i - 1) / 2; }
  int left(int i) { return 2 * i + 1; }
  int right(int i) { return 2 * i + 2; }

  int n; // capacidad
  int s; // tamaño

  int *a; // arreglo

public:

  heap(int);
  ~heap();

void ins(int);
int tout();
int maxChild(int);

int capacity() const { return n; }
int size() const { return s; }

bool empty() const { return s == 0; }
bool full() const { return s == n; }

void print();
};

#endif /* stack_hpp */
//https://dev.to/imnotleo/heap-39no
```
Stack
Published: 2024-03-13 23:39:57

```

#ifndef stack_hpp
#define stack_hpp

#include <stdio.h>
#include <cassert>

class stack {

  int n; // Capacity of stack
  int s; // Size of stack

  int *a; // Dynamic Array of stack

public:

  stack(int);
  ~stack();

  void push(int);
  int pop(void);
  int top(void);

  int capacity() const { return n; }
  int size() const { return s; }
/*
  bool full() const {
    if (s==n) return true;
    else return false;
  }
*/
  bool full() const { return s==n; }
  bool empty() const { return s==0; }

  void print();
};

#endif /* stack_hpp */

```

```

#include "stack.hpp"
#include<iostream>
using namespace std;

stack::stack(int c){

  n = c;
  s = 0;
  a = new int[n];
}

stack::~stack(){

  delete [] a;
}

void stack::push(int x){
  assert(!full());
  a[s++] = x;
}
int stack::pop(){
  assert(!empty());
  return a[--s];
}
int stack::top(){

  assert(!empty());
  return a[s-1];
}

 void stack::print(){
  cout << "[ ";
  for(int i = 0; i < s; i++) cout << a[i] << " ";
  cout << "]\n";
 }

```

```

#include <iostream>
#include "stack.hpp"
using namespace std;
int main(){

  srand((unsigned) time(nullptr));
  
  stack s(10);

  while (!s.full()){
    int x = rand() % 101;

    cout << x << ": ";

    s.push(x);
    s.print();
  }

  cout << "La pila está llena\n\n";
  
  while (!s.empty()) {

    int x = s.pop();

    cout<< x << ": ";
    s.print();
  }

  cout << "La pila está vacia\n\n";

  for (int i = 0; i < 20; i++){
     // inserción
    if (rand () % 2 == 1){

      if (s.full()) cout << "Pila llena\n";
      else {
      int x = rand() % 101;

      cout << "ins " << x << ": ";
      s.push(x);
      s.print();
      }
      //extraccion
    } else {
      if (s.empty()) cout << "Pila vacia\n";
      else {
      int x = s.pop();

      cout << "out " << x << ": ";
      s.print();
      }
    }
  }
  
  return 0;
}

```
All joins in PostgreSQL: Tutorial
Tags: postgres, sql, webdev, beginners
Published: 2024-03-13 23:31:28

{% embed https://youtu.be/FprFu75BoE4 %}

This is a comprehensive guide on all the kinds of joins in Postgres and their use cases.

This will equip you with the knowledge to effectively retrieve data across multiple tables in your Postgres database.

**What you'll learn:**

* Understanding the concept of joins in relational databases.
* Types of joins: Inner Join, Left Join, Right Join, Full Outer Join, Self Join, Cross Join, and Natural Join.
* Practical applications of each join type with real-world scenarios.
* Writing SQL queries to perform various joins in Postgres.

**Prerequisites:**

* Basic understanding of relational databases.
* Familiarity with basic SQL syntax.

**Video Highlights:**

* **Introduction to Joins:**
    * Grasp the purpose of joins in retrieving data from multiple tables.
    * Recognize the role of primary and foreign keys in establishing relationships.
* **Types of Joins Explained:**
    * **Inner Join:** Retrieve rows where a match exists in both tables based on the join condition.
    * **Left Join:** Include all rows from the left table, even if no match is found in the right table (null values are added for unmatched columns).
    * **Right Join:** Similar to left join, but prioritizes the right table.
    * **Full Outer Join:** Combine both left and right joins, including unmatched rows from both tables with null values.
    * **Self Join:** Join a table with itself to compare data within the same table.
    * **Cross Join:** Produces a Cartesian product, listing all possible combinations of rows from two tables (often used in conjunction with other joins).
    * **Natural Join:** Automatically joins tables based on columns with identical names.
* **Practical Examples:**
    * **Employee-Department Database Scenario:** Apply different join types to retrieve relevant employee information and their departments.
    * **Complex Queries:** Explore using joins with multiple tables for intricate data analysis.