anujeet.swain
Mon Nov 04 2024
Query Defaults in React-Query
Any option we pass to React-Query besides the
• Passing
• Setting default options for subset of queries using
• Setting default options within useQuery for fine grain control over specific query.
Each method takes precedence over the others in this order.
#react-query #customizing-defaults
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.
const queryClient = new QueryClient(
defaultOptions: {
queries: {
staleTime: 10 * 1000
}
}
}
• Setting default options for subset of queries using
Fuzzy Matching
by setQueryDefaults
method
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.
useQuery({
queryKey: ['todo'],
staleTime: 10 * 1000,
});
Each method takes precedence over the others in this order.
#react-query #customizing-defaults
amber.srivastava
Mon Nov 04 2024
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:
•
•
Example
#CCT1JMA0Z
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
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
nitturu.baba
Wed Oct 30 2024
Git Rebase:
It is similar to merge, but the difference is merging brings the changes from the
Rebasing applies your branch’s commits on top of the
• 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
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
nitturu.baba
Tue Oct 29 2024
To avoid N+1 queries in Rails, you can use the
Suppose you have two models:
By using
This approach loads
#CU6U0R822
.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.
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:
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
nitturu.baba
Mon Oct 28 2024
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.
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
ayasha.pandey
Fri Oct 25 2024
onDelete: Cascade
in Prisma automatically deletes the child records when a parent record is deleted.
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:
await prisma.user.delete({ where: { id: 123 } })
All their posts are automatically deleted too!
#prisma #schema
nived.hari
Fri Oct 25 2024
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
2. Run the following command
3. Modify the rebase file. Git will open a text window with last 3 commits
•
• To squash the second and third commits into the first one, change
4. After we save and exit, another text editor will pop-up with commit messages
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
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
git checkout branch-name
2. Run the following command
git rebase -i HEAD~3
3. Modify the rebase file. Git will open a text window with last 3 commits
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
# 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
nived.hari
Thu Oct 24 2024
Concerns
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern module provided by Rails.
They help in organizing and reusing code across controllers and models by extracting common functionality into modules.
There are 2 main blocks in a concern
1.
1. Any code inside this block is evaluated in the context of the including class.
2. if sample class includes a concern, anything inside the included block will be evaluated as if it was written inside the sample class.
3. This block can be used to define Rails macros like validations, associations, and scopes.
4. Any method you create here becomes instance methods of the including class.
2.
1. Any methods that you add here become class methods on the including class.
Example:
typically concerns are located in
Including this concern in a controller:
#RubyOnRails #concerns #CU6U0R822
A Rails concern is just a plain Ruby module that extends the ActiveSupport::Concern module provided by Rails.
They help in organizing and reusing code across controllers and models by extracting common functionality into modules.
There are 2 main blocks in a concern
1.
included
1. Any code inside this block is evaluated in the context of the including class.
2. if sample class includes a concern, anything inside the included block will be evaluated as if it was written inside the sample class.
3. This block can be used to define Rails macros like validations, associations, and scopes.
4. Any method you create here becomes instance methods of the including class.
2.
class_methods
1. Any methods that you add here become class methods on the including class.
Example:
typically concerns are located in
app/controllers/concerns
or app/models/concerns
module ExampleConcern
extend ActiveSupport::Concern
included do
# any code that you want inside the class
# that includes this concern
end
class_methods do
# methods that you want to create as
# class methods on the including class
end
end
Including this concern in a controller:
class SomeController < ApplicationController
include ExampleConcern
end
#RubyOnRails #concerns #CU6U0R822
adithya.hebbar
Wed Oct 23 2024
Here is how to generate
This will add or generate a
#js #nextjs #seo
robots.txt
in Next.Js - App Router. Add a robots.js
or robots.ts
file in your app directory
import type { MetadataRoute } from 'next'
export default function robots(): MetadataRoute.Robots {
return {
rules: {
userAgent: '*',
allow: '/',
disallow: '/private/',
},
}
}
This will add or generate a
robots.txt
file that matches the Robots Exclusion Standard in the root of app
directory to tell search engine crawlers which URLs they can access on your site.#js #nextjs #seo
ayushsrivastava
Tue Oct 22 2024
We can generate a UUID in Rails using
#CU6U0R822
SecureRandom.uuid
without needing any gem#CU6U0R822
Showing 2 to 5 of 71 results