Hello,
If you are facing the same error, simple steps to fix it, is to just follow the below link topic from Vercel:
Hope this helps to resolve your issue!
Happy learnings.
Hello,
If you are facing the same error, simple steps to fix it, is to just follow the below link topic from Vercel:
Hope this helps to resolve your issue!
Happy learnings.
Hello,
If you are facing error :
Unhandled Runtime Error
TypeError: Failed to construct 'URL': Invalid URL
And you already have following loader ‘imgix’ settings in your next.config.js file
images: {
// loader and path setting for android build to load nextjsimage and also on web on certain scenarios!
loader: 'imgix',
path: '/', // Remove the path prefix for production images
domains: [
'xxx.com',
'*.xxx.com',
'aaa.xxx.com',
'via.placeholder.com',
],
}
To fix this the solution provided here worked out well!
Code snippet solution: source page stackoverflow
const loaderProp =({ src }) => {
return src;
}
<Image
src={currentImage.imageurl}
alt={currentImage.imageurl}
layout="fill"
className={styles.imageSize}
loader={loaderProp}
/>
we just need to add loader prop to the Image tag of next.js component and passdown the callback function which resolves the error above, voila!
Hope this also help you if you are facing this solution in your next.js application.
happy learning!
If you are traveling in Mumbai and are having trouble finding the station QR scan code to book your tickets, here is your handy companion to scan the station QR code and book your tickets using the UTS app.
Your companion: https://utsqrscan.doableyo.com
Download the app from Google Playstore or bookmark the web link 🖇️ now!
Share with your friends and family right now!
#utsqrscan #mumbai #locals #mumbailocals
In the ever-evolving landscape of frontend development, ReactJS stands as a cornerstone technology, continually setting new standards for building dynamic and scalable web applications. As ReactJS continues to evolve with each new release, staying up-to-date with the latest features, best practices, and interview questions is essential for React developers aiming to excel in their careers. Let’s delve into some of the latest ReactJS interview questions, highlighting the cutting-edge trends and techniques shaping the world of React development.
In conclusion, staying abreast of the latest trends and techniques in ReactJS development is essential for React developers aiming to excel in their careers. By mastering the latest ReactJS interview questions and understanding the underlying principles behind them, developers can demonstrate their proficiency in building modern, high-performance web applications with ReactJS. As ReactJS continues to evolve, embracing innovation and continuously learning new concepts will be key to staying ahead in the dynamic world of frontend development.
In today’s fast-paced tech industry, ReactJS has emerged as a dominant force in frontend development. As businesses increasingly rely on ReactJS to build dynamic and interactive user interfaces, the demand for skilled ReactJS developers continues to rise. Whether you’re a seasoned React developer or just starting your journey, preparing for ReactJS interviews is crucial for landing your dream job. To help you ace your next interview, let’s delve into some of the most commonly asked ReactJS interview questions along with detailed explanations and best practices.
In conclusion, mastering ReactJS interview questions requires a solid understanding of React’s core concepts, features, and best practices. By familiarizing yourself with these commonly asked questions and their explanations, you’ll be well-prepared to tackle ReactJS interviews with confidence and demonstrate your expertise in building modern web applications with ReactJS.
Happy coding!
Hello, welcome to the post!
Determining the appropriate fee for software development depends on several factors, including your level of expertise, the complexity of the project, the time and resources required, and market rates in your region. Here’s a general framework to help you calculate your fee:
Remember, it’s essential to find a balance between charging a fair rate for your expertise and skills while remaining competitive in the market. Additionally, always ensure that the fee you charge covers your costs and allows you to make a reasonable profit.
source : Chat GPT AI Tool
Hello,
Welcome to the post.
When I ask AI tool for the question and the response I received is
The choice of the best database for an ecommerce application selling prepaid and annual subscriptions depends on various factors such as scalability, performance, reliability, ease of use, and the specific requirements of your application. Here are some popular databases commonly used for such applications:
Ultimately, the best database for your ecommerce application depends on your specific use case, technical requirements, budget, and familiarity with the technology stack. It’s essential to carefully evaluate the features and trade-offs of each database option before making a decision. Additionally, consider factors such as ease of integration with your chosen programming language, framework, and hosting environment.
Hope this give us the general idea behind choosing the right database in building web applications or mobile applications.
Source: Chat GPT.
Hello,
Welcome to the post, if you are facing similar issue on your webpage or simple app where you are trying to change the HTML input element placeholder text color according to your design or theme and changes are not applying you followed very basic documentation from MDW web docs placeholder
What is causing this issue is simple, I was facing similar issue with search field and I am using Chrome browser mainly as my default browser, so I haven’t check it was behaving right or not, so I was looking for the answers.
I have tried this solution from stakeoverflow added simple snippet from here but it still not showing reflection of change. so I though, I am writing my CSS code using SCSS, maybe I need to add in some other way or format syntax-ly, so stumbled upon on another stakeoverflow page, added the mixin in my scss code, hope to see the reflection of color change to placeholder text of input field, sorry this time it didn’t worked too,
I was wondering how to get the fix, so in my browser inspect window, i saw one selector [type=search] and some styles applying via _reboot.scss file, I tried to open that file from my application it was there, because I am using bootstrap, so its coming through that from node_modules dynamically maybe.
So in my main.scss, file where I was earlier adding css code for placeholder text “Search Author”) color to white, but it was still in dark grey color not taking effects
SCSS code
after I thought and tried to add the placeholder wrapping [type=search] selector it worked like a charm!
Finally worked, placeholder text color change to search type input field in HTML!!!
I hope you will get to learn from this simple issue and try to explore something own to figure out the issue we face.
Something some simple things are hard to figure out due to some companies work hard building great stuff making simple stuffs complicated to be fix later!
Anyways happy learning! Enjoy.
P.S
Later found simple text placeholder color text was not taking effect, maybe scss is not compiling the placeholder css code as default placeholder target selector, added below code to target text field, select and textarea individually and it started working for different parts of the application where used.
Welcome to Post,
Lets learn how to do the thing in the question, assuming you have basic or advance knowledge or learning something of your own to understand the things or you have got stuck due to simple issues of mistakes.
Using jQuery, HTML, Laravel Blade, Controller, Web Route and AJAX.
Lets begin.
Lets we talk first and defined about the HTML form field and its jQuery functionality. (I will be skipping middle parts of the code what it does and how its populated for the form fields ) and we will be using two fields here to show the example : session_date and session_type, which would look like below in the html code. session_type values would be morning, evening and so on for the day session.
<div class="row">
<div class="form-group col-md-3">
<label for="session_date">Session Date:<sup>*</sup> </label>
<input type="date" name="session_date" id="session_date" class="form-control jsSessionDate"
value="{{ old('session_date', now()->format('Y-m-d'))}}"
/>
<!--<div class="text-end"><small class="text-muted"></small></div>-->
</div>
<div class="form-group col-md-3">
<!--<input type="hidden" name="session_type" class="form-control hide mt-1" value="morning" />-->
<label for="session_type">Select Session Type:<sup>*</sup></label>
<select name="session_type" id="session_type" class="form-select text-capitalize jsSessionTypeChange"
>
@foreach ($sessions_types as $ddSession)
<option value="{{ $ddSession }}" {{old('session_type') == $ddSession ? 'selected' : ''}}>{{ $ddSession }}</option>
@endforeach
</select>
</div>
</div>
Once we have the basic fields ready in HTML side we can write the jQuery side of it to fetch the records and make the AJAX call our server side of Laravel Controller.
$(document).on('change', '.jsSessionTypeChange', function(e) {
const { value } = e.target;
const sessionDateVal = $('.jsSessionDate').val();
console.log(value)
if(!value) return;
const $this = $(this);
const payload = {
_token: $('meta[name="csrf-token"]').attr('content'),
};
const sessionType = value || 'morning';
const sessionDate = sessionDateVal ?? {{now()->format('Y-m-d')}};
const baseUrl = window.location.origin+'/ams';
const url = `${baseUrl}/existing-session/${sessionType}/${sessionDate}`;
console.log({url, sessionType, sessionDate});
$.ajax({
url,
type: "get",
cache: false,
}).done(function(resp) {
if(resp) {
console.log({
resp
})
}
})
.fail(function(err) {
console.error("Existing session fetch error: ", err, err.responseText);
});
});
//IGNORE THE CONSOLE LOGS
Here, I am getting values from date filed and select dropdown for session type, on session type change event forming server side api end point url, not using PHP Laravel Blade example with javascript is its very difficult for blade to understand passing dynamic javascript variable to it.
Because PHP code executed on the page load even we defining the blade {{ }} in onChange event function scope. so its looks for that variable and its goes undefined , tried otherways around the then get the error from rotue generation syntax as route is forming dynamically.
So I thought to set back with simple Javascript code for forming the base URL and its endpoint for ajax call to happen.
Giving you context what I said above and for what thing i was trying to do in Javascript of code using Laravel Blade syntax, which didn’t worked out simply.
Try 1:
const type = value || 'morning';
const url = "{{ route('existing-session', ['sessionType' => '${type}']) }}";
$.ajax({
url: url,
// ... rest of your AJAX configuration
});
Try 2:
const type = value || 'morning';
const url = "{{ route('existing-session', ['sessionType' => '${type}']) }}";
$.ajax({
url: url,
// ... rest of your AJAX configuration
});
Try 3: Finally
const type = value || 'morning';
const baseUrl = window.location.origin;
const url = `${baseUrl}/existing-session/${type}`;
$.ajax({
url: url,
// ... rest of your AJAX configuration
});
Okay, now our HTML and JQUERY code is ready, lets quickly add in to our routes/web.php, dynamic route for ajax to work!
// To get existing Session on Create View
Route::get('existing-session/{sessionType}/{sessionDate}', [App\Http\Controllers\EventSessionController::class, 'existingSession'])->name('existing-session');
Now Finally in Controller side, write as method to get the sessionType and sessionDate and pull it the data from database and return as json response to the ajax call. Then we are good to finish!
public function existingSession($sessionType, $sessionDate) {
// Fetch session with today's date and specific session type
if($sessionType !== '' && $sessionDate !== '') {
$existingSession = EventSession::with(['members', 'samagams'])->where('session_type', $sessionType)
->whereDate('session_date', $sessionDate ?? now()->format('Y-m-d'))
->first();
$response = ["data" => $existingSession, "success" => true, "error" => false, "message" => $sessionType." session found for date ".$sessionDate];
} else {
$response = [ "data" => null, "success" => false, "error" => true, "message" => "No existing session found for given session type ". $sessionType ." and date " .$sessionDate];
}
return response()->json($response);
}
Voila, your quick AJAX example ready in Laravel with pulling in data with dynamic passing of data to the GET route.
Hope this gives you hints, idea how to do the things in PHP Laravel.
Thanks for reading the post and happy learning!
Hello, welcome to this precious post on learning of most advance and interview questioned ReactJS Hooks
Topics covered to be learned:
We will learn all this in reverse order so it stays the harder ones more in our mind for longer time or get it clear in our mind for ever lasting.
Each topic can help you to understand and learn about why each hook used in react and it purpose and one use case scenario for detail understandings. (topic maybe cut and shorten for its sweetness for you to read and grasp the main understandings)
The useDebugValue
is not a hook for managing state or performing side effects like other hooks such as useState
, useEffect
, etc. Instead, it is a hook provided by React that allows you to display custom labels for custom hooks in React DevTools. It’s primarily used for debugging purposes to provide more descriptive labels and information about custom hooks when inspecting them in the browser’s development tools.
Use Case: Custom Hook Labeling for Debugging:
When you create custom hooks, they may appear in the React DevTools as “Custom Hook” by default, which might not be very informative when you have multiple custom hooks in your application. useDebugValue
allows you to customize the label displayed in the DevTools for better debugging and understanding.
Here’s an example of how you might use useDebugValue
in a custom hook:
import { useEffect, useDebugValue, useState } from 'react';
// Custom hook to fetch data and display debug value
function useDataFetcher(url) {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
setLoading(true);
try {
const response = await fetch(url);
const jsonData = await response.json();
setData(jsonData);
setLoading(false);
} catch (error) {
console.error('Error fetching data:', error);
setLoading(false);
}
};
fetchData();
}, [url]);
// Use the custom hook's url as the debug value label
useDebugValue(url);
return { data, loading };
}
In this example, we have a custom hook called useDataFetcher
, which fetches data from a given URL using the fetch
API. By using useDebugValue
with the url
parameter as an argument, we’re setting the custom label to the url
. When you inspect this custom hook in React DevTools, you will see the specified label instead of a generic “Custom Hook.”
Open DevTools in your Browser (Chrome) (Windows Keyboard Shortcut : CTL+SHIFT+I )
Remember that useDebugValue
is used only for debugging purposes and has no effect on the actual behavior of the custom hook. It’s a helpful tool for developers to gain more insights into custom hooks during the development process.
The useLayoutEffect
hook in React is similar to the useEffect
hook, but it runs synchronously after the DOM has been updated but before the browser repaints. This makes it suitable for performing DOM manipulations or measurements that require the latest DOM layout information before the user sees the updated content.
Use Case: DOM Measurements and Synchronous Updates:
A common use case for useLayoutEffect
is when you need to interact with the DOM, such as reading element measurements (e.g., width, height, position) or updating the DOM synchronously after a render. This is useful when you need to adjust or animate elements based on their current size or position.
Here’s an example to illustrate its use case:
import React, { useState, useLayoutEffect, useRef } from 'react';
function ElementSizeDisplay() {
const [width, setWidth] = useState(0);
const [height, setHeight] = useState(0);
const divRef = useRef();
useLayoutEffect(() => {
const updateSize = () => {
if (divRef.current) {
setWidth(divRef.current.clientWidth);
setHeight(divRef.current.clientHeight);
}
};
updateSize();
// Attach a resize event listener to update size on window resize
window.addEventListener('resize', updateSize);
// Clean up the event listener on component unmount
return () => {
window.removeEventListener('resize', updateSize);
};
}, []);
return (
<div ref={divRef}>
<p>Width: {width}px</p>
<p>Height: {height}px</p>
</div>
);
}
In this example, we have a ElementSizeDisplay
component that displays the width and height of a div
element. We use useLayoutEffect
to set up a resize event listener and update the state variables width
and height
whenever the div
element’s size changes. We also trigger the initial update immediately after the component mounts.
Using useLayoutEffect
ensures that we get the most up-to-date measurements of the div
element before it’s displayed to the user, which is essential when working with layout calculations or animations that rely on accurate dimensions.
Note: The key difference between useEffect
and useLayoutEffect
is the timing of their execution. While useEffect
runs after the render is committed to the screen, useLayoutEffect
runs before the actual painting, so it can cause the component to block painting if the logic inside it is too slow. For most cases, useEffect
is sufficient, but if you need to make synchronous DOM updates or perform measurements, useLayoutEffect
is the appropriate choice. Just be aware of potential performance implications and use it judiciously.
The useImperativeHandle
hook in React is used to customize the instance value that is exposed when a parent component calls ref
on a child component. It allows you to define what properties or functions of the child component’s instance should be accessible from the parent component.
Use Case: Exposing Child Component’s Functionality to Parent Component:
A common use case for useImperativeHandle
is when you want to allow the parent component to interact with specific methods or properties of a child component directly. This can be useful when the child component encapsulates certain behaviors or actions, and you want to provide an easy-to-use API for the parent component to access those behaviors.
Let’s see an example to illustrate its use case:
import React, { forwardRef, useImperativeHandle, useRef } from 'react';
// Child component that uses useImperativeHandle
const ChildComponent = forwardRef((props, ref) => {
const inputRef = useRef();
// Exposing the focusInput function to the parent component using useImperativeHandle
useImperativeHandle(ref, () => ({
focusInput: () => {
inputRef.current.focus();
},
}));
return <input ref={inputRef} type="text" />;
});
// Parent component
function ParentComponent() {
const childRef = useRef();
const handleButtonClick = () => {
// Using the exposed function to focus the input inside the child component
childRef.current.focusInput();
};
return (
<div>
<ChildComponent ref={childRef} />
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
}
In this example, we have a ChildComponent
that encapsulates an input element and exposes a focusInput
function to the parent component using useImperativeHandle
. The useImperativeHandle
hook is used to define an object with the properties and functions that the parent component can access through the ref
of the ChildComponent
.
The ParentComponent
renders the ChildComponent
and a button. When the button is clicked, the handleButtonClick
function is called, and it, in turn, calls the focusInput
function exposed by the ChildComponent
, focusing the input element inside the child component.
Using useImperativeHandle
can be handy when you want to expose specific functionalities of a child component to its parent, especially when dealing with custom components or third-party libraries. However, be cautious when using this pattern, as it might break encapsulation and lead to a less maintainable codebase. Whenever possible, prefer to manage state and interactions through props and callbacks to maintain a more predictable and React-friendly component architecture.
The useRef
hook in React is used to create a mutable reference to a value that persists across renders. Unlike state variables (useState
), updating a useRef
value does not trigger a re-render. This makes useRef
suitable for storing and accessing mutable values or accessing DOM elements imperatively.
Use Case: Storing Mutable Values:
One of the primary use cases for useRef
is to store mutable values that don’t need to trigger a re-render when updated. Since the component won’t re-render when the useRef
value changes, it can be useful for keeping track of some data that doesn’t affect the component’s visual output.
Here’s an example where useRef
is used to keep track of a previous value:
import React, { useState, useEffect, useRef } from 'react';
function Counter() {
const [count, setCount] = useState(0);
const prevCountRef = useRef();
useEffect(() => {
prevCountRef.current = count;
}, [count]);
const prevCount = prevCountRef.current;
return (
<div>
<p>Current Count: {count}</p>
<p>Previous Count: {prevCount}</p>
<button onClick={() => setCount((prev) => prev + 1)}>Increment</button>
</div>
);
}
In this example, we use useRef
to create a prevCountRef
that keeps track of the previous value of the count
state variable. We update the prevCountRef
using the useEffect
hook whenever count
changes. Since updating prevCountRef
does not trigger a re-render, we can safely access its current value without causing an infinite loop.
Use Case: Accessing DOM Elements:
Another common use case for useRef
is to access and interact with DOM elements directly. Since React components are typically declarative, there might be cases where you need to manipulate a DOM element imperatively (e.g., focusing an input, measuring its size, etc.).
Here’s an example of using useRef
to focus an input element when a button is clicked:
import React, { useRef } from 'react';
function FocusInput() {
const inputRef = useRef();
const handleButtonClick = () => {
inputRef.current.focus();
};
return (
<div>
<input ref={inputRef} type="text" />
<button onClick={handleButtonClick}>Focus Input</button>
</div>
);
}
In this example, we use useRef
to create the inputRef
, which is attached to the input element through the ref
attribute. When the button is clicked, the handleButtonClick
function is called, which uses inputRef.current
to access the underlying DOM element and invoke the focus()
method on it.
Remember that using useRef
for accessing DOM elements should be done sparingly, as it goes against React’s declarative approach. Whenever possible, try to manage component state and behavior through props and state variables to maintain the React flow of data and rendering. However, there are cases where direct DOM manipulation with useRef
can be necessary or more efficient.
The useMemo
hook in React is used for memoizing expensive computations, so they are only recomputed when their dependencies change. It helps optimize the performance of functional components by avoiding unnecessary re-computations of values that haven’t changed between renders.
Use Case: Memoizing Expensive Computations:
The primary use case for useMemo
is when you have a computationally expensive function or calculation that doesn’t need to be re-evaluated on every render, especially if the function relies on some props or state that might remain unchanged for a while.
Let’s see an example to illustrate its use case:
import React, { useMemo, useState } from 'react';
function ExpensiveComponent({ data }) {
// This is a computationally expensive function that we want to memoize
const expensiveResult = useMemo(() => {
let result = 0;
for (let i = 0; i < data.length; i++) {
result += data[i];
}
return result;
}, [data]); // The dependency array contains 'data'
return <div>{expensiveResult}</div>;
}
function App() {
const [dataArray, setDataArray] = useState([1, 2, 3, 4, 5]);
return (
<div>
<ExpensiveComponent data={dataArray} />
<button onClick={() => setDataArray([1, 2, 3, 4, 5])}>Update Data</button>
</div>
);
}
In this example, ExpensiveComponent
takes an array called data
as a prop and computes the sum of its elements. The computation can be costly, especially if the data
array is large.
By using useMemo
with the data
array as a dependency, we ensure that the expensiveResult
is only recalculated when the data
array changes. So, when the parent component (App
) renders and updates the dataArray
, ExpensiveComponent
will not recompute the sum unless the dataArray
changes.
useMemo
should be used when the computation is relatively expensive and depends on certain inputs (props or state) that might not change often. It’s essential to remember that using useMemo
comes with some overhead, so you should only use it when the performance benefits outweigh the costs.
It’s also worth noting that the improvement in performance gained by using useMemo
depends on the nature of the computation and the size of the data. For simple or small computations, the performance gain might be negligible, and in such cases, using useMemo
might not be necessary. Always profile and measure your application’s performance to determine the most effective optimizations.
The useReducer
hook in React is used for managing more complex state logic in functional components. It is an alternative to using the useState
hook when the state has a complex structure or when the state transitions depend on previous state values. useReducer
follows the same principles as the standard Reducer
concept in JavaScript, similar to how it works with the Array.reduce
method.
Use Case: Managing Complex State Logic:
The primary use case for useReducer
is when you need to handle state changes that are more involved and involve multiple sub-values or when you have actions that depend on the previous state. It’s beneficial when the state transitions are not straightforward and need to be calculated based on existing state.
Here’s an example to illustrate its use case:
import React, { useReducer } from 'react';
// Reducer function
function reducer(state, action) {
switch (action.type) {
case 'INCREMENT':
return { count: state.count + 1 };
case 'DECREMENT':
return { count: state.count - 1 };
default:
return state;
}
}
function Counter() {
// useReducer returns the current state and a dispatch function to send actions.
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'INCREMENT' })}>Increment</button>
<button onClick={() => dispatch({ type: 'DECREMENT' })}>Decrement</button>
</div>
);
}
In this example, the useReducer
hook is used to manage the state of a simple counter component. The reducer
function defines how state transitions should happen based on different action types. The state is initialized with { count: 0 }
, and clicking the buttons dispatches actions to increment or decrement the count.
useReducer
provides a structured way to handle more complex state updates, especially when you need to consider multiple factors before updating the state. It can be particularly useful when working with state machines, form handling, or managing state in contexts and reducers for more extensive applications.
However, for simpler cases where the state doesn’t involve complex transitions or doesn’t depend on the previous state, useState
may be more suitable and easier to manage. Choose the right approach based on the specific requirements and complexity of your component’s state management.
The useCallback
hook in React is used to memoize functions, which helps to optimize the performance of functional components that rely on callbacks, especially when passing them down to child components. Memoization means that the function returned by useCallback
will only change if its dependencies change, otherwise, the same memoized function instance will be reused.
The syntax of the useCallback
hook is as follows:
const memoizedCallback = useCallback(callbackFunction, dependencies);
callbackFunction
: The function that you want to memoize.dependencies
(optional): An array of dependencies. If any of these dependencies change, the memoized callback will be recomputed; otherwise, it will be reused.Use Case: Preventing Unnecessary Re-renders:
In React, passing down new function references to child components can lead to unnecessary re-renders. For example, consider a parent component rendering multiple instances of a child component, and each child component receives a callback prop from the parent. If the parent component creates a new function instance for the callback prop on every render, each child component will think that its prop has changed, resulting in re-renders even if the actual logic of the callback hasn’t changed.
Using useCallback
, you can avoid this behavior by memoizing the callback function:
import React, { useCallback } from 'react';
import ChildComponent from './ChildComponent';
function ParentComponent() {
const handleClick = useCallback(() => {
// Callback logic
}, []);
return (
<div>
<ChildComponent onClick={handleClick} />
</div>
);
}
By providing an empty dependency array ([]
) as the second argument to useCallback
, we ensure that the handleClick
function remains the same across re-renders, preventing unnecessary re-renders of the child component.
Remember, while useCallback
can help with performance optimizations in certain situations, it’s essential to use it judiciously. Overusing useCallback
might lead to less predictable behavior and unnecessary overhead. As with all performance optimizations, it’s best to measure and profile your application to identify actual performance bottlenecks before applying optimizations like useCallback
.
Hope this helps you in interview preparation and your successful selection.
Drop us your love and kindness, by sharing this article. Thank you!