TILs - 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.

Published
Author
user-image
Ayasha Pandey
System Analyst
useFetch is a Nuxt composable used to fetch data in a server-side or client-side context, ensuring data is fetched before rendering the component. It is primarily used for making HTTP requests and providing a reactive way of managing the fetched data.

useAsyncData is very similar to useFetch, but it allows for fetching data asynchronously, without blocking the server-side rendering process. It's useful when you want to fetch data in a non-blocking way, enabling the page to render without waiting for the data.

Key Difference:
useFetch fetches data synchronously during SSR, blocking the rendering process until the data is available.
useAsyncData fetches data asynchronously, allowing the page to render without waiting for the data.
#fetch #nuxt #useFetch #useAsyncData
Published
Author
user-image
Nitturu Baba
System Analyst
In Rails, forms can be created in two ways: with a URL (using form_with url: ...) or with a model (using form_with model: ...).
But, when to use which?

Form with URL (form_with url: ...)
This form is used when you specify a URL directly and typically use it for non-resourceful actions or when you don’t have a specific model associated with the form.

Code

<%= form_with url: some_path, method: :post do |form| %>
  <%= form.text_field :some_field %>
  <%= form.submit "Submit" %>
<% end %>


The form_with_url is suitable for forms that don't map directly to a model, like search forms, login forms, or other custom actions etc.

Form with Model (form_with model: ...)
This form is bound to an instance of a model, allowing Rails to automatically set the form action (URL) and method (POST or PATCH) based on whether the model is a new record or an existing one.

Code

<%= form_with model: @record do |form| %>
  <%= form.text_field :name %>
  <%= form.submit %>
<% end %>


Rails determines the correct URL and HTTP method based on the record's state:
New Record: If @record.new_record? is true, Rails generates a POST request to the model’s create route.
Existing Record: If @record.persisted? is true, Rails generates a PATCH request to update the model’s update route.
The form_with_model is suitable for forms that directly interact with a model, such as forms for creating or editing a resource (like User, Post, etc.).

#ruby on rails
Published
Author
user-image
Adithya Hebbar
System Analyst
To update a user’s password in AWS Cognito and set it as permanent, we can use the AWS CLI with the following admin command:

Code

aws cognito-idp admin-set-user-password \
    --user-pool-id <pool-id> \
    --username <cognito-username> \
    --password <password> \
    --permanent


#auth #aws #cognito
Published
Author
user-image
Anujeet Swain
System Analyst
Query Defaults in React-Query
Any option we pass to React-Query besides the query key can have its default values and can be set by following ways:
• Passing defaultOptions object to query client as global defaults.

Code

const queryClient = new QueryClient(
 defaultOptions: {
  queries: {
   staleTime: 10 * 1000
  }
 }
}


• Setting default options for subset of queries using Fuzzy Matching by setQueryDefaults method

Code

queryClient.setQueryDefaults(
 ['todos','list'],
 {staleTime: 10 * 1000}
) 
//This sets default stale time of 10secs for all the matched queries having keys 'todos' and 'list'


• Setting default options within useQuery for fine grain control over specific query.

Code

useQuery({
 queryKey: ['todo'],
 staleTime: 10 * 1000,
});


Each method takes precedence over the others in this order.
#react-query #customizing-defaults
Published
Author
user-image
Amber Srivastava
Promise.allSettled() :

Purpose: Executes multiple promises and waits for all of them to settle (either resolve or reject).
Returns: A promise that resolves with an array of objects. Each object has:
status: Either "fulfilled" or "rejected".
value: The resolved value (if fulfilled) or reason: The rejection reason (if rejected).
Example

Code

const promises = [
  Promise.resolve(1),
  Promise.reject('Error'),
  Promise.resolve(2),
];

Promise.allSettled(promises).then((results) => {
  results.forEach((result) => {
    if (result.status === 'fulfilled') {
      console.log('Result:', result.value);
    } else {
      console.log('Error:', result.reason);
    }
  });
});

Output :
Result: 1
Error: Error
Result: 2


#CCT1JMA0Z
Published
Author
user-image
Nitturu Baba
System Analyst
Git Rebase:

It is similar to merge, but the difference is merging brings the changes from the main branch into your current branch by creating a merge commit that combines the histories of both branches.

Rebasing applies your branch’s commits on top of the main branch, making it look as if your work was started from the latest main commit.

• First pull the latest changes of main branch.
• Then navigate to the working branch
• run the command git rebase main
• if there any conflicts resolve and continue rebase.
• After rebasing completely, force push the changes.
#git
Published
Author
user-image
Nitturu Baba
System Analyst
To avoid N+1 queries in Rails, you can use the .includes method to eager-load associated records, which reduces the number of database calls.

Suppose you have two models: Order and Item, where an Order has many Items. Without eager-loading, querying each order’s items individually would lead to N+1 queries.


Code

orders = Order.all 
orders.each do |order| 
  puts order.items # Each order triggers a separate query for items
end


By using .includes, Rails will fetch all associated items in a single additional query:


Code

orders = Order.includes(:items)
orders.each do |order|
  puts order.items # No extra query is triggered here
end


This approach loads Order records in one query and then fetches all associated items in a second query, avoiding the N+1 issue.

#CU6U0R822
Published
Author
user-image
Nitturu Baba
System Analyst
before_action runs a specified method before the controller action. It’s useful for tasks that need to happen before executing the main action, such as authentication, setting up a resource, or ensuring permissions.


after_action runs a specified method after the controller action has executed. It’s useful for tasks that need to happen after the response is rendered, such as logging activity, tracking metrics, or cleaning up resources.



Code

class PointsController < ApplicationController
  before_action :set_user_points, only: [:show, :redeem]
  after_action :update_points_history, only: [:redeem]

  def show
    # Show points balance
  end

  def redeem
    # Redeem points logic
  end

  private

  def set_user_points
    @points = current_user.points
  end

  def update_points_history
    # Log the points redemption action
  end
end



In the above example set_user_points will execute before the controller actions show and redeem. update_points_history will execute after the redeem action.

#CU6U0R822
Published
Author
user-image
Ayasha Pandey
System Analyst
onDelete: Cascade in Prisma automatically deletes the child records when a parent record is deleted.

Code

model User {
  id    Int     @id @default(autoincrement())
  posts Post[]
}

model Post {
  id     Int   @id @default(autoincrement())
  userId Int
  user   User  @relation(fields: [userId], references: [id], onDelete: Cascade)
}


Now when you delete a user:

Code

await prisma.user.delete({ where: { id: 123 } })


All their posts are automatically deleted too!

#prisma #schema
Published
Author
user-image
Nived Hari
System Analyst
Combining Commits with Git Squash
Squashing commits allows us to combine multiple related commits into a single one, helping to keep the commit history clean.

Let's say if we want to combine 3 separate commits which are related to same thing into one clean commit,

1. Checkout the branch

Code

git checkout branch-name


2. Run the following command

Code

git rebase -i HEAD~3


3. Modify the rebase file. Git will open a text window with last 3 commits

Code

pick 7f9d4bf first commit
pick 3f8e810 second commit
pick ec48d74 third commit


pick means to keep the commit as is.
• To squash the second and third commits into the first one, change pick to squash / s for those commits.
4. After we save and exit, another text editor will pop-up with commit messages

Code

# This is a combination of 3 commits.
# The first commit message:

fix for bug

# Commit message for #2:
Updated this

# Commit message for #3:
Added comments & updated README


Simply saving this will result in a single commit with a commit message that is a concatination of all 3 messages.
We can choose which one we want, or we can create a new message entirely.
5. Complete the Rebase
After saving, we now have a single commit representing the previous three.

#git #rebase

Showing 13 to 15 of 83 results

Ready to Build Something Amazing?

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

  • Address
    2nd Floor, Zee Plaza,
    No. 1678, 27th Main Rd,
    Sector 2, HSR Layout,
    Bengaluru, Karnataka 560102
  • Contact

    +91-9731601276