teleren/devto huggingface dataset:
Beginner's Guide to Writing Cleaner React Code with TanStack-Query
Tags: webdev, javascript, beginners, programming
Published: 2024-05-12 09:51:21

Showing data obtained from external sources is a fundamental 

Here are the steps to start using React Query to enhance your code:

---


## **1.Understand the difference between client state and server state**


Client state exists in the browser, such as form state, dark mode, or whether a modal is open or closed. Server state probably resides in a database and is served asynchronously.

Always use React Query for server state. For client state, use native hooks like useState or useReducer.


## **2. Install React-Query in your project**

Follow the [installation instructions](https://tanstack.com/query/latest/docs/framework/react/installation) and remember to set up the query [client provider](https://tanstack.com/query/latest/docs/framework/react/quick-start)


## **3. Replace data fetching code and states in your code with the useQuery hook  Instead of writing this:**


```ts
 const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    async function fetchData() {
      try {
        const response = await fetch('https://rickandmortyapi.com/api/character');
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        const result = await response.json();
        setData(result.results);
      } catch (err) {
        setError(err);
      } finally {
        setLoading(false);
      }
    }

    fetchData();
  }, []);
```

write this:

```ts
function fetchRickAndMortyCharacters() {
  return fetch('https://rickandmortyapi.com/api/character')
    .then(response => {
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      return response.json();
    })
    .then(data => data.results);
}

  const { data, isLoading, isError, error } = useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
```

The data you need to render will be in the destructured data. Here is an example of how you can render the result:

```ts
 if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error: {error.message}</p>;
  if (!data) return <p>No data available</p>;

  return (
    <ul>
      {data.map(character => (
        <li key={character.id}>{character.name}</li>
      ))}
    </ul>
  );
```

## **4.Convert the useQuery hook into a custom hook**


For better reusability, abstract this into a custom hook:

```ts
export function useRickAndMortyCharacters() {
  return useQuery(['rickAndMortyCharacters'], fetchRickAndMortyCharacters);
}
```

now, from any component, you can just call the custom hook like so:

```ts
const { data, isLoading, isError, error } = useRickAndMortyCharacters();
```
That's it! If you want to go any further, read the docs and play around with different query options or with mutations.

Thanks for reading!
Top 10 Video Editing Software: From CapCut to Professional Suites
Published: 2024-05-12 09:28:22

**CapCut:** CapCut is a popular mobile video editing app developed by ByteDance, known for its user-friendly interface and powerful editing features. It's widely used for creating and editing videos on smartphones.
**Adobe Premiere Pro:** Adobe Premiere Pro is a professional video editing software widely used by filmmakers, videographers, and content creators. It offers a comprehensive set of editing tools, advanced effects, and seamless integration with other Adobe Creative Cloud apps.
**Final Cut Pro X:** Final Cut Pro X is a professional video editing software developed by Apple for macOS users. It provides advanced editing features, intuitive timeline editing, and seamless integration with other Apple products.
**DaVinci Resolve:** DaVinci Resolve is a powerful video editing software with professional-grade color correction, audio post-production, and visual effects capabilities. It's available in both free and paid versions, making it accessible to a wide range of users.
**Adobe Premiere Elements:** Adobe Premiere Elements is a simplified version of Adobe Premiere Pro designed for casual users and beginners. It offers easy-to-use editing tools, automated features, and guided tutorials to help users create polished videos quickly.
**iMovie:** iMovie is a video editing software developed by Apple for macOS and iOS users. It provides basic editing tools, intuitive interface, and seamless integration with other Apple devices, making it popular among casual users and beginners.
**HitFilm Express:** HitFilm Express is a free video editing and visual effects software with advanced editing tools, compositing features, and a wide range of visual effects. It's suitable for both beginners and advanced users looking to create professional-quality videos.
**Sony Vegas Pro:** Sony Vegas Pro is a professional video editing software with a robust set of editing tools, advanced effects, and support for a wide range of video formats. It's popular among professional editors and filmmakers for its flexibility and powerful features.
**Filmora:** Filmora is a user-friendly video editing software with a wide range of editing tools, creative effects, and built-in templates. It's suitable for beginners and casual users looking to create high-quality videos without a steep learning curve.
**CyberLink PowerDirector:** CyberLink PowerDirector is a feature-rich video editing software with intuitive editing tools, advanced effects, and support for 360-degree video editing. It's suitable for both beginners and advanced users looking to create professional-quality videos.
**_In my 10-year professional video editing career, I always use CapCut. It's the best tool for me._** Download CapCut: [Visit this website](https://capcuttemplatee.co.in/).
Using Valibot for Recursive Schema Validation
Tags: typescript, demo, valibot
Published: 2024-05-12 09:16:29

[Valibot's playground for the code demo](https://valibot.dev/playground/?code=JYWwDg9gTgLgBAKjgQwM5wG5wGZQiOAcg2QBtgAjCGQgbgCh6BjCAO1XgFERlhSBlJgAsApjzgBeTADoOUYKwDmACgDaGaSAUAZEUphDlARgCUAGhljepZSYC6Jhi3bwACmlQB3aABNBo8SkNOQUVdU0dPUUDY3MZLVZdfUMADntHRhgATzAROABVVBEofysAFRy8qQBvejg4YT4fKD0AfgAuAqKS4XLKhnqrPk6NAElWMABXGAAebNyIbDhua1KeAD4BuDAPbygfEelxqdn5kUW4d1QvXzXkTfoAX0ZnDi7iu8OAITQRO5nCh9ejwKrl1pIZBAKAArERMGDKWr1RqkZp6Q4QMAwYBsMjKDSkZAALyyylsknBgJ6AWQJnMdTgQ1InRWfDuZgZO2uewOl12t2ByA5jwyzDYbxaqEmpHgQVkyGwIncUCKyip7LgSMZPGGRGhyFYIgAAiIAB7IcCkETSFggQgc+pcm77TqEIwAJgAzAAWACsADYAOwpe1PUWvCBW6SkCAqSXSmCOIA)

## Recursive Type in TypeScript

TypeScript allows defining recursive types. For example, consider the following `User` interface:

```typescript
interface User {
 children?: User;
 email: `${string}@${string}`;
 password: string;
}
```

## Using Valibot for Schema Validation

What if you use a schema library, like [Zod](https://zod.dev/) or [Valibot](https://valibot.dev/)? The schema has been built on value-level, and you cannot assign the variant to its property inside the declaration.

```typescript
import * as v from 'valibot';

const EmailSchema = v.string([v.minLength(1), v.email()]);
const PasswordSchema = v.string([v.minLength(1), v.minLength(8)]);
// const UserSchema?
```

### Recursive Schema

Base on the Author's reply in [this issue](https://lnkd.in/gs-s3puw), you can use `v.lazy(() => UserSchema)` and to create a type of the `UserSchema` as a type param to the `v.BaseSchema` genre as a type inference of the `UserSchema`:

```typescript
type UserSchemaType = {
 children?: UserSchemaType;
 email: v.Input<typeof EmailSchema>;
 password: v.Input<typeof PasswordSchema>;
}

const UserSchema: v.BaseSchema<UserSchemaType> = v.object({
 children: v.optional(v.lazy(() => UserSchema)),
 email: EmailSchema,
 password: PasswordSchema,
});
```
League Linq - Sports league management
Tags: sport, platform, club, app
Published: 2024-05-12 08:55:14

League LINQ is a sports league management platform. We help club organizers and managers operate their leagues and tournaments—everything from registration, payments, roster management, scheduling, messaging, playoffs, and more. Designed with a mobile focus and ease of use, League LINQ is a leader for season-long or tournament play management with a full suite of features.

[https://leaguelinq.com](https://leaguelinq.com)
Find Your Perfect Gathered Skirt at Maldire Dance Wear
Published: 2024-05-12 08:52:08

<p>Are you tired of searching high and low for the perfect gathered skirt? Look no further! Maldire Dance Wear has got you covered. In this article, we will explore the world of gathered skirts and why Maldire Dance Wear is the ultimate destination for all your dancewear needs.</p>
<h2>What Makes a Gathered Skirt Perfect?</h2>
<p>A perfect gathered skirt is not just any skirt. It is a piece of art that adds grace and elegance to your dance moves. It should be comfortable, lightweight, and flow beautifully with every step you take. At Maldire Dance Wear, we understand the importance of a perfect gathered skirt and strive to provide you with the best quality skirts that meet all your requirements.</p>
<h2>The Maldire Dance Wear Difference</h2>
<p>At Maldire Dance Wear, we believe that every dancer deserves to feel confident and empowered on stage. That is why we go the extra mile to ensure that our gathered skirts are not only visually stunning but also crafted with the utmost care and attention to detail. Our team of skilled artisans handcraft each skirt, ensuring that every stitch is perfect and every pleat is impeccable.</p>
<h2>A Wide Range of Options</h2>
<p>We understand that every dancer has their own unique style and preferences. That is why we offer a wide range of gathered skirts to suit every taste. Whether you prefer a classic black skirt, a vibrant floral print, or a bold and dramatic design, we have something for everyone. Our skirts come in various lengths, sizes, and fabrics, allowing you to find the perfect fit for your body type and dance style.</p>
<h2>Unleash Your Creativity</h2>
<p>At Maldire Dance Wear, we believe that dance is an art form that allows you to express yourself freely. That is why we encourage our customers to unleash their creativity and customize their <a href="https://www.maldire.com/shop/sweatleisure"><strong>gathered skirt</strong></a> . Whether you want to add extra layers, incorporate unique embellishments, or experiment with different colors, our team will work closely with you to bring your vision to life.</p>
<h2>Conclusion</h2>
<p>Finding the perfect gathered skirt can be a daunting task, but with Maldire Dance Wear, it becomes a breeze. Our commitment to quality, craftsmanship, and customer satisfaction sets us apart from the rest. So why wait? Visit our website or store today and find your perfect gathered skirt at Maldire Dance Wear.</p>
The Thing Called AI; A Series
Tags: writing, beginners, ai
Published: 2024-05-12 08:52:08

*Episode 1: Introduction*
The term, “Artificial Intelligence” has indeed made waves in the tech field, drawing the attention of people from all walks of life.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/rds5812pg51akirkf88b.jpg)
According to https://www.wikipedia.org Artificial Intelligence, or AI, as it is widely called,“...is intelligence exhibited by machines, particularly computer systems”. The concept of AI entails computer systems that possess the ability to carry out complex tasks that, historically, only a human could do. Such tasks include reasoning, making decisions, and applying such decisions to problem-solving. In simple terms, AI is the science of enabling machines to fit in the shoes of humans.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/8bczezz5oap6ypttaum6.jpg)
The technology of AI has made waves in the human world, evolving with the tide of time and to an appreciable extent, meeting the insatiable needs of our contemporary society. AI has made notable impacts in the various spheres of life including the medical field, the educational field, the agricultural sector, etc. It is safe to say here that AI is Tech's most popular birth and this offspring is just getting started with humans.
In this series, I will be walking you down AIville as we will be learning, unlearning, and relearning the thing called AI. Also, we will get to see if this “panacea” has any drawbacks or inconsistencies and also discuss its most likely impact on our green home in times to come.
Move the Minimize, Maximize and Close buttons to the left in Ubuntu
Published: 2024-05-12 08:17:38


1. Open a terminal by pressing Ctrl + Alt + T.
2. Open a terminal by pressing Ctrl + Alt + T.

```
gsettings set org.gnome.desktop.wm.preferences button-layout 'close,minimize,maximize:'

```
If you want to revert the changes and move the buttons back to the right, you can use the following command:

```
gsettings set org.gnome.desktop.wm.preferences button-layout 'appmenu:minimize,maximize,close'

```
FCM notification issue
Published: 2024-05-12 08:14:04

Hi,

I'm flutter developer, I want to build chat & video calling app. 
My app almost done, but face couple of issue about FCM notification.

Sometimes, FCM silent notification not comming, I'm using flutter_callkit_incoming.

- App open Foreground (Working fine)
- App Background (Working maximum time)
- App Terminated (App not working)

Any one help me, please.

Advance thanks
Halfway House Game: A Path to Recovery and Reintegration
Published: 2024-05-12 07:56:45

As players progress through the game, they encounter various challenges and obstacles that mirror the real-life hurdles faced by individuals in recovery. These challenges may include finding employment, securing stable housing, managing finances, and rebuilding relationships with family and friends. Through strategic decision-making and resource management, players must navigate these obstacles while staying true to their goals of sobriety and rehabilitation.

One of the key features of the Halfway House Game is its emphasis on community support and collaboration. Players have the opportunity to interact with one another, forming friendships, alliances, and support networks within the virtual halfway house. By working together, players can share resources, offer advice, and provide encouragement to one another, fostering a sense of camaraderie and belonging.

In addition to navigating external challenges, players also face internal struggles and temptations on their journey to recovery. The game simulates the temptations of substance abuse, negative influences from peers, and the psychological toll of past traumas. Through mindfulness exercises, therapy sessions, and group discussions, players learn to recognize and cope with these triggers in healthy and constructive ways.

As players progress through the game, they earn points and rewards for achieving milestones such as maintaining sobriety, securing employment, and repairing damaged relationships. These rewards serve as tangible markers of progress and provide players with a sense of accomplishment and motivation to continue their journey.

https://gamerule.io
Netlify Dynamic Site Challenge: Mini Gallery
Tags: netlifychallenge, devchallenge, webdev, nextjs
Published: 2024-05-12 07:43:36

*This is a submission for the [Netlify Dynamic Site Challenge](https://dev.to/challenges/netlify): Visual Feast + Build with Blobs + Clever Caching. (All 3 prompts)*


## What I Built
Introducing Mini Gallery, a cosy corner on the internet where you can share and appreciate beautiful images. Dive into a stream of captivating visuals posted by our community members, and join in on conversations with comments and likes. Finally, feel free to share your images and be the centre of attention.


## Demo
Link: https://mini-gallery.netlify.app/

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

![Home Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/e42z3bx55x4rngte0mab.png)


![Create Post Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5b3s6sthkqn5hvh7oq0j.png)

![Image Post 1](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/1ir7916ng9cclcg7s2l2.png)

![Image Post 2](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/dqjywkk2npzaaqra6yrb.png)


![Profile Page](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/37v1xkg6m68p85p75g5o.png)



## Platform Primitives
### Netlify Image CDN
I used the Netlify Image CDN to optimize images. Thanks to Netlify's Next.js runtime, this happens automatically when we use the `next/image` element. Image optimization helps us by caching all the images so we don't have to wait for the server on every request.

### Netlify Blobs
I used Netlify Blobs to store all the images uploaded by the users. I save the image and some metadata to Netlify Blob whenever a new post is created. Then, I pick up the image from the blob storage and serve it on demand.

### Cache-Control
I have implemented Netlify's CDN Cache-Control to cache all the images posted by the users with tags. Caching helps improve speeds and reduces the load on the server. Then, whenever a user deletes their post, I use the `purgeCache` function to delete the post from the CDN cache.

## Tech Stack
-   [Next.js](https://nextjs.org)
-   [ShadCN UI](https://ui.shadcn.com)
-   [Radix UI](https://www.radix-ui.com)
-   [Tailwind CSS](https://tailwindcss.com)
-   Postgres (With [Neon DB](https://neon.tech))
-   [Prisma](https://prisma.io)
-   [Kinde Auth](https://kinde.com)
-   [Netlify](https://netlify.com)

## Wrapping Up
I had a lot of fun building this. I will open-source the code and make another post to share what I have learned while building this project.

Edit: [Link to Tutorial](https://dev.to/ridays2001/how-to-build-a-simple-instagram-clone-with-nextjs-and-netlify-1id)

Thanks!
Week 10!
Published: 2024-05-12 07:01:21

Almost done with the internship! And I almost completed my task when they added another set for me to learn but this time one of the task that they added to my planner was I only need to observe and my trainer explained to me how they do it in every step, good thing I have a recorder app that I can just turn on every time we have a discussion so that I can just review it later on. I was also taught another task by another trainer from our department and it was easy after some time. Also met again with the Vietnam agent, there was some lapses in communication since he sometimes not able to really explain what he wants to say but we were able to communicate and understand each other so it was all good.
Do You Meditate? 🧘‍♂️
Tags: discuss
Published: 2024-05-12 07:00:00

Is meditating worth the effort in today's fast-paced world? If you meditate, do you notice that it works to increase mental clarity and focus throughout the day?

Share your thoughts on balancing mindfulness with the demands of modern life.
<br>
Follow the DEVteam for more discussions and online camaraderie!
{% embed https://dev.to/devteam %}
Introducing VisualFeast: Dynamic Image Management with Netlify
Tags: netlifychallenge, javascript, nextjs, devchallenge
Published: 2024-05-12 06:55:48

Hey Devs!

Exciting news from Team Spark: we've taken on the Netlify Dynamic Site Challenge and emerged with VisualFeast, a dynamic image management solution. With VisualFeast, users can effortlessly add, retrieve, update, and delete images across albums.

Here's what sets VisualFeast apart:

Netlify Image CDN: Enjoy optimized images and a sleek gallery layout thanks to Netlify's Image CDN.
Netlify Blobs: Seamlessly store and retrieve blob objects while simplifying metadata management.
Clever Caching: VisualFeast leverages Netlify's cache control to optimize load times and enhance user experience.
Check out VisualFeast now and revolutionize your image management!

Cheers,
Team Spark
Team Members: @adityanithariya, @adityaagupta, @abhishekshaarmaa
GitHub: https://github.com/adityanithariya/VisualFeast
Deployed Site: https://visualfeast.netlify.app
The magical number game
Tags: perl, python, theweeklychallenge
Published: 2024-05-12 06:19:39

## Weekly Challenge 268

Each week Mohammad S. Anwar sends out [The Weekly Challenge](https://theweeklychallenge.org/), a chance for all of us to come up with solutions to two weekly tasks. My solutions are written in Python first, and then converted to Perl. It's a great way for us all to practice some coding.

[Challenge](https://theweeklychallenge.org/blog/perl-weekly-challenge-268/), [My solutions](https://github.com/manwar/perlweeklychallenge-club/tree/master/challenge-268/sgreen)

## Task 1: Magic Number

### Task

You are given two arrays of integers of same size, `@x` and `@y`.

Write a script to find the magic number that when added to each elements of one of the array gives the second array. Elements order is not important.

### My solution

For input via the command line, I take a list of integers and then split the list in two. Calling the Python function directly takes two list.

For this task I numerically sort the two lists `x` and `y`. I then calculate the different between the first values in each list, and store this as `diff`.

I then loop through each position in the list to ensure the difference between the integers in that position in each list is `diff`. If it isn't, I exit early.

```python
def magic_number(x: list, y: list) -> int | None:
    x = sorted(x)
    y = sorted(y)

    diff = y[0] - x[0]

    for i in range(len(x)):
        if y[i] - x[i] != diff:
            return None

    return diff
```

### Examples

```bash
$ ./ch-1.py 3 7 5 9 5 7
2

$ ./ch-1.py 1 2 1 5 4 4
3

$ ./ch-1.py 2 5
3
```

## Task 2: Number Game

### Task

You are given an array of integers, `@ints`, with even number of elements.

Write a script to create a new array made up of elements of the given array. Pick the two smallest integers and add it to new array in decreasing order i.e. high to low. Keep doing until the given array is empty.

### My solution

This is relatively straight forward, so doesn't need much explanation. For this task, I sort the list and then swap each pairs of numbers (1st and 2nd, 3rd and 4th, etc).

Both Python and Perl support the `x, y = y, x` syntax to swap numbers without using a temporary value.

```python
def numbers_game(ints: list) -> list:
    ints = sorted(ints)

    for i in range(0, len(ints), 2):
        ints[i], ints[i+1], = ints[i+1], ints[i]

    return ints
```

### Examples

```bash
$ ./ch-2.py 2 5 3 4
(3, 2, 5, 4)

$ ./ch-2.py 9 4 1 3 6 4 6 1
(1, 1, 4, 3, 6, 4, 9, 6)

$ ./ch-2.py 1 2 2 3
(2, 1, 3, 2)
```
Week 9!
Published: 2024-05-12 06:55:17

Another week with the same tasks and the same people in the office. However this time, I had to let the other intern from other school observe me while I do my daily task since our manager told him that he will be learning the tasks from our department which is Warehouse and since I am doing the first task I was told that I let the other intern observed me and show him how to do the task.
Week 8!
Published: 2024-05-12 06:52:05

Already in week 8! My tasks are still the same. I have 1 task that I need to do daily and four times a day starting from my shift. Also had to do another task every Monday which I always do after I do  my first task and every another specific task that I need to do every Friday. This is what I usually do in my internship and everyone in the office makes it even better.