Fueling Curiosity, One Insight at a Time

At Codemancers, we believe every day is an opportunity to grow. This section is where our team shares bite-sized discoveries, technical breakthroughs and fascinating nuggets of wisdom we've stumbled upon in our work.

Jul 4, 2024
When implementing password and confirmPassword field with react-hook-form and zod for validation, you might need to figure out a way to run the validation for both the fields simultaneously. With the default approach, or the simple implementation you would notice that upon updating password field, the validation for confirm password won't kick in and vice versa.

One solution for these would be to use Controller from react-hook-form and use superRefine to run your validation simultaneously.

Snippet:


// validation Schema
import { z } from 'zod';

// Define the schema
const schema = z.object({
  password: z.string().min(8, 'Password should be at least 8 characters long'),
  confirmPassword: z.string().min(8, 'Password should be at least 8 characters long'),
}).superRefine((data, ctx) => {
  if (data.password !== data.confirmPassword) {
    ctx.addIssue({
      code: 'custom',
      path: ['confirmPassword'],
      message: 'Passwords do not match',
    });
  }
});

export default schema;




// form component
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import schema from './schema'; // Import the schema

const PasswordForm = () => {
  const { handleSubmit, control, formState: { errors } } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = (data) => {
    console.log('Form Data:', data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Password</label>
        <Controller
          name="password"
          control={control}
          render={({ field }) => (
            <input
              type="password"
              {...field}
              placeholder="Enter your password"
            />
          )}
        />
        {errors.password && <span>{errors.password.message}</span>}
      </div>

      <div>
        <label>Confirm Password</label>
        <Controller
          name="confirmPassword"
          control={control}
          render={({ field }) => (
            <input
              type="password"
              {...field}
              placeholder="Confirm your password"
            />
          )}
        />
        {errors.confirmPassword && <span>{errors.confirmPassword.message}</span>}
      </div>

      <button type="submit">Submit</button>
    </form>
  );
};

export default PasswordForm;


Second solution, just in case if you're not using the react-hook-form's Controller would be using the trigger and touchedFields from react-hook-form and using react's classic useEffect:



// component with Schema
import React, { useEffect } from 'react';
import { useForm } from 'react-hook-form';
import { zodResolver } from '@hookform/resolvers/zod';
import { z } from 'zod';

const schema = z.object({
  password: z.string().min(8, 'Password should be at least 8 characters long'),
  confirmPassword: z.string().min(8, 'Password should be at least 8 characters long'),
}).superRefine((data, ctx) => {
  if (data.password !== data.confirmPassword) {
    ctx.addIssue({
      code: 'custom',
      path: ['confirmPassword'],
      message: 'Passwords do not match',
    });
  }
});

const PasswordForm = () => {
  const { handleSubmit, register, trigger, formState: { errors, touchedFields } } = useForm({
    resolver: zodResolver(schema),
  });

  const onSubmit = (data) => {
    console.log('Form Data:', data);
  };

  useEffect(() => {
    if (touchedFields.password) {
      trigger('password');
    }
  }, [trigger, touchedFields.password]);

  useEffect(() => {
    if (touchedFields.confirmPassword) {
      trigger('confirmPassword');
    }
  }, [trigger, touchedFields.confirmPassword]);

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <div>
        <label>Password</label>
        <input
          type="password"
          {...register('password')}
          placeholder="Enter your password"
        />
        {errors.password && <span>{errors.password.message}</span>}
      </div>

      <div>
        <label>Confirm Password</label>
        <input
          type="password"
          {...register('confirmPassword')}
          placeholder="Confirm your password"
        />
        {errors.confirmPassword && <span>{errors.confirmPassword.message}</span>}
      </div>

      <button type="submit">Submit</button>
    </form>
  );
};

export default PasswordForm;


Happy Coding!!! 🙂

#reactHookForm #react #formValidation #zod #useEffect
vaibhav.yadav
Vaibhav Yadav
Senior System Analyst
Jul 3, 2024
To connect to the PostgreSQL RDS instance using psql:


psql -h ${postgres_host} -U "${postgres_username}" -d ${postgres_database} -W


where, ${postgres_host}: variable representing the PostgreSQL host or db endpoint

#devops #PostgreSQLConnection #rds
soniya.rayabagi
Soniya Rayabagi
Jul 2, 2024
Install powerful monitoring tools, Grafana and Prometheus
Grafana:
• Install with Homebrew: brew install grafana
• Start the service: brew services start grafana
• Access at https://localhost:3000 (default login: admin/admin)
• Stop the service: brew services stop grafana
Prometheus:
• Install with Homebrew: brew install prometheus
• Configure prometheus.yml:


global:
  scrape_interval: 10s

scrape_configs:
  - job_name: 'prometheus'
    static_configs:
      - targets: ['localhost:9090']


where -> scrape_interval: 10s: Prometheus will collect metrics from all defined targets every 10 seconds.
scrape_configs: This section defines how Prometheus should scrape metrics from targets.
• Start with configuration: prometheus --config.file=prometheus.yml
• Access at https://localhost:9090
#devops #grafana #prometheus
soniya.rayabagi
Soniya Rayabagi
Jul 1, 2024
overscroll-behavior in CSS

The overscroll-behavior CSS property controls what happens when you reach the boundary of a scrollable area. It's useful for managing scroll chaining and preventing unwanted browser behaviors like the "bounce" effect or "pull to refresh."

Usage
- Default (auto): Normal scroll behavior.
- Contain: Stops scroll chaining; keeps default behavior within the element.
- None: Prevents both scroll chaining and the default overflow behavior.

Examples
Prevent underlying content from scrolling:

.scroll-container {
height: 220px;
overflow: auto;
overscroll-behavior-y: contain;
}

Disable overscroll effects:

html {
margin: 0;
overscroll-behavior: none;
}

#css #alignment-issue #frontend
giritharan
Giritharan
System Analyst
Jun 25, 2024
Beacon API

Reliable way to send asynchronous data to a server, especially during page unload events. The Beacon API lets us send small amounts of data asynchronously and non-blockingly to a server. Unlike traditional solution like fetch, the Beacon API ensures that the data is sent before the page unloads and runs to completion. The browser ensures that the request is initiated before the page is completely unloaded. This includes scenarios where the user closes the tab, navigates to another page, or reloads the page. The primary goal is to deliver the data reliably. The browser ensures that the data transfer completes before the document is discarded.



window.addEventListener('beforeunload', () => {
const data = JSON.stringify({ userId: '12345' });
navigator.sendBeacon('/logout', data);
});

ashwanikumarjha
Ashwani Kumar Jha
Senior System Analyst
Jun 25, 2024
In JavaScript, console.time is a method that helps you measure the time it takes for a specific block of code to execute. It's like a stopwatch for your code.


// Start the timer 
console.time('myTimer');
for (let i = 0; i < 1000000; i++) { 
 // Some code here 
}
// Stop the timer 
console.timeEnd('myTimer');


So, when you run this code, you'll see something like: "myTimer: 1.358ms"

#javascript
adithya.hebbar
Adithya Hebbar
System Analyst
Jun 25, 2024
Performance API

Seems super useful for tracking web performance, it let us measure various performance metrics of web pages, like how long specific operations take.

1. performance.now()
â—¦ Provides the current time in milliseconds with high precision, can be useful for measuring how long specific tasks take.
2. PerformanceEntry
â—¦ Object representing a metric. It includes:
▪︎ navigation: Information about page loads.
▪︎ resource: Data on loaded resources like scripts and images.
▪︎ mark: User-defined timestamps.
▪︎ measure: Duration between two marks.
3. PerformanceNavigationTiming
â—¦ Specific type of PerformanceEntry for page navigation metrics.
â—¦ Tells us if a page load is due to a navigation, reload, or history action.
â—¦ eg properties: domComplete, domContentLoadedEventEnd, type.
Probable use Cases:
• Can help us analyze how long different parts of the page load take.
• Can help us check how long it takes to load each resource.
• Can help us determine if a page is reloaded or newly navigated.
#performance #browser
ashwanikumarjha
Ashwani Kumar Jha
Senior System Analyst
Jun 20, 2024
EJS, the templating engine for JavaScript, allows us to generate HTML markup with plain JavaScript.

By default, EJS escapes any HTML entities in the output to prevent issues such as cross-site scripting. This is done by replacing characters like <, >, &, and " with their respective HTML entity codes.

For example:



- `&` is replaced with `&`
- `<` is replaced with `<`
- `>` is replaced with `>`
- `"` or `'` (double or single quote) is replaced with `&quot;` or `&#39;` respectively.


Unescape HTML entities with <%- %>

If we want EJS to output our data without escaping HTML entities, replace <%= %> with <%- %>. This instructs EJS to render the data as unescaped.
ashwanikumarjha
Ashwani Kumar Jha
Senior System Analyst
Jun 20, 2024
My Rails application is named xyz. When I tried to create a scaffold with the same name as the application, it caused a below error.


The name 'Xyz' is either already used in your application or reserved by Ruby on Rails. Please choose an alternative or use --skip-collision-check or --force to skip this check and run this generator again.


To fix this, I changed the module name in application.rb to abc. After making this change, everything worked. It's always best to avoid using the same name for both the model and the application.

#rails-naming-convention #rails
giritharan
Giritharan
System Analyst
Jun 19, 2024
After pushing my changes to the Fly, I noticed that my Application JS controller wasn't being found. The problem was due to an incorrect line in app/javascript/controllers/application.js. It originally had:



import { application } from "./application";


To fix it, I changed it to:



import { application } from "controllers/application";


These changes ensured that the request was directed to the correct location, and the Stimulus JS controller started working.


#stimulus #assert-not-loading #rails
giritharan
Giritharan
System Analyst

Showing 20 to 22 of 82 results

Ready to Build Something Amazing?

Codemancers can bring your vision to life and help you achieve your goals