⏱ 0:01est. 30 min
Publicissapient
/**
* 1. What is React? How it is different from Angular?
* 2. What the different ways you make an API call on react
* XMLHttpRequest.
* Fetch API.
* Axios.
* 3. Explain the total React Flow and why it is called as a Single Page application with one way data binding.
* One-way means that the binding happens in one direction. In this case, changes in the data automatically update the UI, but changes in the UI do not automatically update the data. That’s why it is referred to as one-way data binding.
* React achieves one-way data binding by using state and props.
* https://www.youtube.com/watch?v=m_mtV4YaI8c
* constructor //Called when a component is created
* static getDerivedStateFromProps(props, state) // allows us to copy props into state
* {
* if (props.seed && state.seed != props.seed) {
* return {
* seed: props.seed,
* counter: props.seed,
* }
* return null;
* }
* }
* componentDidMount() // do network requests, handle initial loading of the component
* shouldComponentUpdate(nextProps, nextState) //true by default
* {
* if (nextProps.ignoreProp && this.props.ignoreProp != nexProps.ignoreProp) {
* // -- donot render
* return false;
* }
* return true;
* }
* getSnapshotBeforeUpdate(prevProps, prevState) // allows to store position of list-view or text areas dom-component, you can pass on to componentDidUpdate, redefine those after the render
* render
* componentDidUpdate(prevProps, prevState, snapshot) {} // called after render, call network requests
* componentWillUnmount() {} // gets called when component is removed from the dom
* componentDidCatch(error, info) {this.setState({error,info})} // gracefully handle error in downstream components
*
* 4. How can you pass data from child to parent? Write an example
* Callbacks - https://dev.to/parnikagupta/one-way-data-binding-in-react-30ea
*
* 5. How are Class component different from Functional
*
* 6. What is shadow Dom and how it is different from Virtual
* Shadow DOM is a web standard that offers a way to encapsulate style and markup in web components
* Hidden dom attached to dom
* css will not leak
* event will also not leak
* Not supported by Edge
* // Attach Shadow Tree in Vanilla JS
* const el = document.createElement('div);
* const shadowRoot = el.attachShadow({mode: 'open'});
* shadowRoot.innerHTML = '<h1>I belong to Shadow DOM</h1>';
* // Query elements in shadow tree
* el.shadowRoot.querySelector('h1');
* https://www.youtube.com/watch?v=K5i9zMzVlzM
*
* 7. What is context API? can we have multiple providers for different context we make
* https://stackoverflow.com/questions/53346462/react-multiple-contexts
* https://builtin.com/software-engineering-perspectives/react-api
*
* 8. Code TODO
* To Do InProgress Completed
* Task1 Task4 Task5
* Task2
* Task3
*
* 9. What are Render props?
* By encapsulating behavior in a component and using a render prop to determine what to render, you can reuse this component in multiple places in your application.
* import React from 'react';
const List = ({ data, render }) => (
<ul>
{data.map((item, index) => (
<li key={index}>{render(item)}</li>
))}
</ul>
);
export default function App() {
const fruits = ['Apple', 'Banana', 'Cherry'];
return (
<List data={fruits} render={fruit => <p>{fruit}</p>}/>
);
}
* 10. Different lifecycle methods -> An console.log statement based on that
* 11. What are the different React hooks i have used
* 12. Explain UseEffect Hook
* 13. Make a timer component that auto decreases by 1 every 1 second
* 14. What is the use of useMemo? useCallback ? React.memo?
const allPrimes = React.useMemo(() => {
const result = [];
for (let counter = 2; counter < selectedNum; counter++) {
if (isPrime(counter)) {
result.push(counter);
}
}
return result;
}, [selectedNum]);
// UseCallback
const functionOne = function() {
return 5;
};
const functionTwo = function() {
return 5;
};
console.log(functionOne === functionTwo); // false
const handleMegaBoost = React.useCallback(() => {
setCount((currentValue) => currentValue + 1234);
}, []);
// React.memo
Wrap a component in memo to get a memoized version of that component. This memoized version of your component will usually not be re-rendered when its parent component is re-rendered as long as its props have not changed.
Usage: Skipping re-rendering when props are unchanged
useMemo is a React Hook that lets you cache the result of a calculation between re-renders.
Usage: Skipping expensive recalculations
15. Write your own Memoization function
https://www.iamtk.co/writing-a-memoization-function-from-scratch
function memoize(fn) {
const cache = new Map();
return (...args) => {
const key = JSON.stringify(args);
if (cache.has(key)) {
return cache.get(key);
}
const result = fn(...args);
cache.set(key, result);
return result;
};
}
16. Make a custom Input hook that is reusable
https://sst.dev/chapters/create-a-custom-react-hook-to-handle-form-fields.html
import { useState, ChangeEvent, ChangeEventHandler } from "react";
interface FieldsType {
[key: string | symbol]: string;
}
export function useFormFields(
initialState: FieldsType
): [FieldsType, ChangeEventHandler] {
const [fields, setValues] = useState(initialState);
return [
fields,
function (event: ChangeEvent<HTMLInputElement>) {
setValues({
...fields,
[event.target.id]: event.target.value,
});
return;
},
];
}
17. Explain HOC
a higher-order component is a function that takes a component as an argument and returns a new component that wraps the original component.
import React from 'react';
import ReactDOM from 'react-dom';
const withLoading = (WrappedComponent) => {
class WithLoading extends React.Component {
state = {
isLoading: true,
};
componentDidMount() {
setTimeout(() => {
this.setState({ isLoading: false });
}, 2000);
}
render() {
return (
<WrappedComponent
{...this.props}
loading={this.state.isLoading}
/>
);
}
}
WithLoading.displayName = `withLoading(${WrappedComponent.displayName || WrappedComponent.name})`;
return WithLoading;
};
const MyComponent = ({ loading }) => (
<div>
{loading ? <p>Loading...</p> : <p>Hello, world!</p>}
</div>
);
const MyComponentWithLoading = withLoading(MyComponent);
ReactDOM.render(
<MyComponentWithLoading />,
document.getElementById("root")
);
18. What is compound component pattern
a pattern in React, where several components are used together such that they share an implicit state that allows them to communicate with each other in the background.
https://blog.logrocket.com/understanding-react-compound-components/
19. Questions on React Router
React Router is a library that helps developers manage and navigate different routes in their React applications.
Yes, it is possible to use React Router with server-side rendering. The way to do this is to use the StaticRouter component on the server, and then use the BrowserRouter component on the client.
Named components are simply React components that have been given a name attribute. This is used by React Router to automatically match up the component with the corresponding route.
<
path=”/some-path”
render={(matchProps) => (
)}
/>
20. How Redux Works?
21. Need of middlewares in Redux
Redux Middleware allows you to intercept every action sent to the reducer so you can make changes to the action or cancel the action.
Middleware helps you with logging, error reporting, making asynchronous requests, and a whole lot more.
Middleware in Redux is a way to extend custom functionality; this gives extra features to the existing ReduxIt provides third-party extension with points between the dispatching of action and the moment it reaches the reducer.
const loggerMiddleware = (store) => (next) => (action) => {
console.log("action", action);
next(action);
};
22. Explain Error Boundaries / Write a sample error boundary structure
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error, errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
23. How do you optimize a React Component
24. React Testing - Gave me to write a sample test for a input with a div where value of input is displayed
import {render, screen} from "@testing-library/react";
describe('Test', () => {
it('should show text', () => {
render(<App />);
const link = screen.getByText(/learn more/i);
expect(link).toBeInTheDocument();
})
})
25. Typescript questions / Webpack
26. Difference between SSG vs SSR
27. What is NextJS / Gatsby and how it is useful as compared to React.
28. What are service workers? Explain usecase
29. What is tree shaking / Babel / proptypes
*/
/**
ROUND 1
// ErrorBoundary
import React, { useEffect } from "react";
// @testing-library/react // render, scren, fireEvent
// jest --- js/typescript/vue/react, jest.fn()
// react router -- react-router-
// webpack -->
// host the npm -> registry -> npm, git, private
// apikey
// .npmrc -> -apikey- .env
import useFetch from "./useFetch";
// import "./styles.css"; // sass/scss/tailwindCSS/postCSS/MUI sm/md//StyleComponent
// 1 show list of pokemon as select view
// 2. make call show abilities from details as list item
// inline style
// StyleComponent
export default function App() {
const [data, error, loading] = useFetch("https://pokeapi.co/api/v2/pokemon");
const [pokemonData, setPokemonData] = React.useState(null);
const [abilities, setAbilities] = React.useState([]);
async function getData() {
const response = await fetch("https://pokeapi.co/api/v2/pokemon");
const data = await response.json();
setPokemonData(data.results);
}
React.useEffect(() => {
getData();
}, []);
const fetchDetail = async (url) => {
const response = await fetch(url);
const data = await response.json();
setAbilities(data.abilities);
};
// if (loading) return <h1>Loading</h1>;
// if (error) return <h1>{error}</h1>;
// if (data) return <h1>{JSON.stringify(data)}</h1>;
// -> ErrorBoundary
return (
// <ErrorBoundary>
<div className="App" style={{ textAlign: "center" }}>
<h1>Working?</h1>
Selectbox for pokemon
{pokemonData !== null && (
<select
onChange={(e) => {
fetchDetail(e.target.value);
}}
>
{pokemonData.map((p) => (
<option key={p.name} value={p.url}>
{p.name}
</option>
))}
</select>
)}
Component for loading abilities
{Boolean(abilities.length) && (
<ul>
{abilities.map(({ ability }) => {
return <li key={ability.name}> {ability.name}</li>;
})}
</ul>
)}
</div>
// </ErrorBoundary>
);
}
import { useEffect, useState } from "react";
export default function (url) {
const [loading, setLoading] = useState(false);
const [data, setData] = useState(null);
const [error, setError] = useState(null);
const fetchInformation = async () => {
try {
setLoading(true);
setError(null);
const response = await fetch(url);
const data = await response.json();
setData(data?.results);
} catch (e) {
console.error(e);
setError(e.message);
} finally {
setLoading(false);
}
};
useEffect(() => {
fetchInformation();
}, []);
return [data, loading, error];
}
*/
/**
* Round 2 Expected questions
* ROUND 2 - HTML / CSS / JS
1. What are semantic elements and how it is useful?
- Semantic HTML elements are those that clearly describe their meaning in a human- and machine-readable way.
- Elements such as <header>, <footer> and <article> are all considered semantic because they accurately describe the purpose of the element and the type of content that is inside them.
List of new semantic elements
- <article>
- <aside>
- <details>
- <footer>
- <header>
- <main>
- <mark>
- <nav>
- <section>
- <summary>
- <time>
2. What do mean by request life cycle?
- HTTP requests serve as the foundation of communication between web APIs and their clients, enabling the exchange of data and resources.
- 3 Parts of a HTTP Request
- Request Line: The request line specifies the HTTP protocol being used and communicates the specific resource or action the client is requesting from the server
- Body (Optional): The request body, although optional, provides additional information that the server may require.
- Request Headers: The request headers are where vital information about the request is conveyed. These headers, or metadata, accompany the request to provide context and details.
- https://requestly.io/blog/life-cycle-of-a-http-request/
Life Cycle of the request
- First, we connect to our server (foodcourt) by entering an URL, and our browser gives a request to connect to a socket (just like calling for a waiter). After that, the request reaches the socket(waiter) and is accepted, i.e., port 80 if we use HTTP.
- The process of establishing a connection between a client and a server is done by a process called a 3-way handshake. Firstly, our first handshake is executed by our client sending an SYN (synchronization) segment request to our server so as to tell the server that it wants to connect to the server. Now if we have a valid request, our server also sends an SYN+ACK(acknowledgment) request back to our client (The ACK part is for telling that it accepts the SYN request by our client to create a connection over which the client can send data, The SYN part is because the server also wants to create a connection over which it can send data to the client so essentially trying to create a DUPLEX connection).In response to the servers SYN request now, in turn, our client sends an ACK request, and voila, our connection is established.
// https://www.linkedin.com/pulse/life-cycle-http-request-mamun-hoque/
3. How does browser understand your JS code?
- JavaScript is an interpreted language, which means that the computer understands it while running it. Some languages get processed before running, this is called compiling, but not JavaScript. The computer can just interpret JavaScript on the fly. The "engine" that understands JavaScript will be called the interpreter here.
// - https://medium.com/@mustafa.abdelmogoud/how-the-browsers-understand-javascript-d9699dced89b
4. What is async and defer in script tags?
* - async and defer both load JavaScript asynchronously without render blocking
* - but async executes as soon as possible while defer runs in sequence toward the end of the loading process, just before the DOMContentLoaded event. https://pagespeedchecklist.com/async-and-defer
* Async
- Downloads in the background at a low priority (same as defer)
- Can interrupt page rendering to execute
- Executes as soon as possible and in no particular order
- <script async src="super-high-priority.js"></script>
Defer
- Downloads in the background at a low priority (same as async)
- Won't interrupt page rendering to execute
- Executes in sequence just before the DOMContentLoaded event
- <script defer src="general-stuff.js"></script>
5. What is the use of preconnect in css?
- The preconnect keyword for the rel attribute of the <link> element is a hint to browsers that the user is likely to need resources from the target resource's origin, and therefore the browser can likely improve the user experience by preemptively initiating a connection to that origin. Preconnecting speeds up future loads from a given origin by preemptively performing part or all of the handshake (DNS+TCP for HTTP, and DNS+TCP+TLS for HTTPS origins).
- <link rel="preconnect"> will provide a benefit to any future cross-origin HTTP request, navigation or subresource. It has no benefit on same-origin requests because the connection is already open.
## Browser Resource Hints: preload, prefetch, and preconnect
// https://www.debugbear.com/blog/resource-hints-rel-preload-prefetch-preconnect
- preload – load content that's required for the intial render
- prefetch - load content that may be needed to render the next page
- preconnect - establish a server connection without loading a specific resource yet
6. What is CSS specificity?
- Specificity is the algorithm used by browsers to determine the CSS declaration that is the most relevant to an element, which in turn, determines the property value to apply to the element.
- specificity hierarchy - lists selector types from the highest specificity to the lowest specificity.
// https://blog.hubspot.com/website/css-specificity
- ID selectors - #my-id
- Class selectors - .my-class
attribute selectors - p[target],
and pseudo-class selectors - button:hover)
- Type selectors: div
- Universal selector: *
7. What are CSS Selectors and CSS rules?
- A CSS selector is the first part of a CSS Rule. It is a pattern of elements and other terms that tell the browser which HTML elements should be selected to have the CSS property values inside the rule applied to them. The element or elements which are selected by the selector are referred to as the subject of the selector.
8. What are mixins? How are JS in CSS helpful?
Benefit: Avoid repetition
Benefit: Create dynamic styles
Benefit: Modularize your code
Drawback: Overuse and complexity
Drawback: Output and performance
Drawback: Compatibility and maintenance
https://levelup.gitconnected.com/css-in-js-pros-and-cons-of-styling-in-javascript-16071f201c7d
import React from 'react';
import { css } from '@emotion/react';
const buttonStyles = css`
display: flex;
align-items: center;
justify-content: center;
`;
const MyButton = () => (
<button css={buttonStyles}>Click Me</button>
);
9. CSS TASK GRID
Task 1 Task 4
Task 2 Task 5
Task 3 Task 6
- Use grid for layouts
- Use flexbox of inner elements
- Grid
- container display:grid
: Properties
- grid-template-columns
- grid-template-rows
- grid-gap
- grid-auto-rows
- grid-auto-columns
- grid-template-areas
- justify-content
- align-items
- items (children)
: Properties
- grid-column
- grid-row
- grid-area
- align-self
- justify-self
// http://localhost:3000/learning-grid-system
https://stackoverflow.com/questions/74818767/transpose-table-css-grid
// grid-template-rows: repeat(3, 1fr);
// grid-auto-flow: column;
// gap: 10px;
// .item:nth-child(3n+0) {}
@media (max-width: 500px) {
.container {
grid-template-columns: 1fr;
grid-auto-flow: row;
}
}
Flex: You can create 1 column layouts, can be either row or columns
Grid: You can create two-dimensional layouts with rows and columns
10. What is scopechain in js? How js engine reads scopechain
11. What is hoisting? Difference between variable and function hoisting
12. Basic difference between forEach and map?
13. Explain the this keyword?
14. Call / Apply / bind with an example for each
15. Major difference between ES5 and ES6 javascripts
16. Gave me a task on Even handling and Dom manipulation - Increment / decrement using vanilla js
17. Explain Encapsulation in Javascipt? How closures are useful in JS
18. sum(2) (3)(4) (5) (6)(n)
19. What are promises how promises are different from async- await
20. How do you do error handling?
21. Difference between promise.all / promise.race
// https://dev.to/swarnaliroy94/methods-of-promise-all-any-finally-o2e
22. Write a JS code to check an entered email is Valid or not
// https://stackoverflow.com/questions/46155/how-can-i-validate-an-email-address-in-javascript
function looksLikeMail(str) {
var lastAtPos = str.lastIndexOf('@');
var lastDotPos = str.lastIndexOf('.');
return (lastAtPos < lastDotPos && lastAtPos > 0 && str.indexOf('@@') == -1 && lastDotPos > 2 && (str.length - lastDotPos) > 2);
}
Explanation:
lastAtPos < lastDotPos: Last @ should be before last . since @ cannot be part of server name (as far as I know).
lastAtPos > 0: There should be something (the email username) before the last @.
str.indexOf('@@') == -1: There should be no @@ in the address. Even if @ appears as the last character in email username, it has to be quoted so " would be between that @ and the last @ in the address.
lastDotPos > 2: There should be at least three characters before the last dot, for example a@b.com.
(str.length - lastDotPos) > 2: There should be enough characters after the last dot to form a two-character domain. I'm not sure if the brackets are necessary.
23. What are prototypes in JS
24. What are function compositions / HOF
// https://medium.com/@akhilanand.ak01/function-composition-in-javascript-exploring-the-power-of-compose-4114da8b9875
- The composition of a function is an operation where two functions say f and g generate a new function say h in such a way that h(x) = g(f(x)).
const add5 = (x) => x + 5;
const multiplyBy3 = (x) => x * 3;
const subtract10 = (x) => x - 10;
const composedFunction = compose(subtract10, multiplyBy3, add5);
const result = composedFunction(7);
console.log(result); // Output: 36
const compose = (...functions) => {
return (input) => {
return functions.reduceRight((acc, fn) => {
return fn(acc);
}, input);
};
};
25. DRY / SOLID principles
26. What do you mean by Web Accessibility? Explain
27.What is caching mechanism & service workers?
28. How do you optimise your website for better load times
29. Webpack / Babel / code splitting
30. What is minification / git commands / eslint
// https://codepen.io/codeclassifiers/pens/public
CSS Grid
https://codepen.io/codeclassifiers/pen/oNaPpgE
// https://codepen.io/codeclassifiers/pen/yLRrXvM
async function fetchCarts(callback) {
const response = await fetch("https://fakestoreapi.com/carts?limit=2");
const responseBody = await response.json();
const cartData = responseBody;
console.log("cartData", cartData);
const combinedProducts = [].concat(...cartData.map(cart => cart.products));
console.log("combinedProducts", combinedProducts)
}
async function fetchProductData(callback, productId) {
const response = await fetch(`https://fakestoreapi.com/products/${productId}`);
const responseBody = await response.json();
callback(responseBody);
}
fetchCarts(callback = (products)=>{
console.log("products", products);
});
const submitButton = document.getElementById("submit");
submit.addEventListener("onclick", function(){
console.log("button clicked");
})
** https://codepen.io/codeclassifiers/pen/JjwjgZe?editors=1011
// https://fakestoreapi.com/products
// Promise.all[] -> https://fakestoreapi.com/products/1
// https://fakestoreapi.com/carts?limit=2
// https://fakestoreapi.com/products/${productId}
// async function fetchCarts(callback) {
// const response = await fetch("https://fakestoreapi.com/carts?limit=2");
// const responseBody = await response.json();
// const cartData = responseBody;
// let combinedProducts = [];
// cartData.map((cartItem)=>{
// combinedProducts = [...cartItem.products];
// })
// callback(combinedProducts);
// }
// fetchCarts(async(products)=>{
// console.log("products", products);
// const productsItem = [];
// const responses = await Promise.all(
// products.map(async item => {
// const res = await fetch(
// `https://fakestoreapi.com/products/${item.productId}`
// ); // Send request for each product
// const responseBody = await res.json();
// return responseBody;
// })
// );
// // console.log("responses", responses);
// })
// https://fakestoreapi.com/carts?limit=2
// https://fakestoreapi.com/products/${productId}
async function fetchCart(callback) {
const response = await fetch("https://fakestoreapi.com/carts?limit=2");
const responseBody = await response.json();
// console.log("response", responseBody);
let products = [];
responseBody.map((productItem)=>{
products = [...products,...productItem.products]
});
// console.log("products", products);
callback(products);
}
fetchCart(async (products)=>{
const results = await Promise.all(
products.map(async productItem => {
const response = await fetch(`https://fakestoreapi.com/products/${productItem.productId}`);
const responseBody = await response.json();
return responseBody;
})
);
console.log("resultsArray", results);
});
// fetchCarts(async(products)=>{
// console.log("products", products);
// const productsItem = [];
// const responses = await Promise.all(
// products.map(async item => {
// const res = await fetch(
// `https://fakestoreapi.com/products/${item.productId}`
// ); // Send request for each product
// const responseBody = await res.json();
// return responseBody;
// })
// );
// // console.log("responses", responses);
// })
// https://codepen.io/randpharoah/pens/showcase
Currying
// https://codepen.io/codeclassifiers/pen/yLQjmmN
function add(x) {
function innerAdd(y) {
// Check if the next value is provided or not
if (y === undefined) {
// If not, return the accumulated sum
return x;
} else {
// If yes, add the value and return a new curried function
return add(x + y);
}
}
// Return the innerAdd function, which can be called with the next parameter or to retrieve the result
return innerAdd;
}
// Define a utility function to retrieve the result directly
function getResult(fn) {
console.log("fn", fn)
return fn();
}
console.log(getResult(add(1)(2)));
console.log(getResult(add(1)(2)(3)));
// Difference between PUT and PATCH method in Javascript
/*
The PUT method is used to completely replace an existing resource with
the new representation provided in the request
The PATCH method is used to partially update an existing resource.
POST /users/1
{
"username": "sera",
"email": "sera@domain.example"
}
PUT /users/1
{
"username": "sera12",
"email": "sera23@gmail.com" // new email address
}
PATCH /users/1
{
"email": "sera23@gmail.com" // new email address
}
const arrayOfElements = [2, 4, 6, 7, 10];
// Implement polyfill for map method
const mappedArray = arrayOfElements.map((item) => {
return item * 2;
});
console.log("original array", arrayOfElements);
console.log("mapped array", mappedArray);
Array.prototype.myMap = function (callback) {
// console.log("this", this);
var newArray = [];
for (var i = 0; i < this.length; i++) {
newArray.push(callback(this[i]));
}
return newArray;
};
const myMappedArray = arrayOfElements.myMap((item) => {
return item * 2;
});
console.log("myMappedArray", myMappedArray);
const filteredArray = arrayOfElements.filter((item) => {
return item % 2 === 0;
});
console.log("filteredArray", filteredArray);
Array.prototype.myFilter = function (callback) {
var newArray = [];
for (var i = 0; i < this.length; i++) {
if (callback(this[i])) {
newArray.push(this[i]);
}
}
return newArray;
};
const myFilteredArray = arrayOfElements.myFilter((item) => {
return item % 2 === 0;
});
console.log("myFilteredArray", myFilteredArray);
const reducedArray = arrayOfElements.reduce((total, num) => total * num);
console.log("reducedArray", reducedArray);
Array.prototype.myReduce = function (callback, initialValue) {
var accumulator = initialValue;
for (var i = 0; i < this.length; i++) {
if (accumulator != undefined) {
accumulator = callback(accumulator, this[i]);
} else {
accumulator = this[i];
}
}
return accumulator;
};
const myReducedArray = arrayOfElements.myReduce((total, num) => total * num);
console.log("myReducedArray", myReducedArray);
*/
/**
* ROUND 2
* // console.log("here");
// // Create a vanilla js application that consumes the
// // https://fakestoreapi.com/products?sort=asc API and
// // displays a list of products in ascending order based on price.
// // The application should also include a dropdown to allow the user to change the sorting of the products between ascending and descending.
// // When the user changes the sorting order, the application should update the query parameter value and fetch the products with the new sorting order.
// // util
// class CustomFetch {
// async myFetch(url) {
// await fetch(url);
// }
// async fetMultiple([url1, url2]) {}
// }
// class ProductsAPI {
// async getProducts(sortType = "asc") {
// console.log("calling products", fetch);
// const response = await new CustomFetch().myFetch(
// `https://fakestoreapi.com/products?sort=${sortType}`
// );
// // const products = await response.json();
// // return products;
// }
// }
// Promise.all([new ProductsAPI().getProducts(), new ProductsAPI().getProducts()])
// .then((result) => console.log(result))
// .catch((err) => {
// console.log(err);
// });
// Promise.any([new ProductsAPI().getProducts(), new ProductsAPI().getProducts()])
// .then((result) => console.log(result))
// .catch((err) => {
// console.log(err);
// });
// Promise.race([new ProductsAPI().getProducts(), new ProductsAPI().getProducts()])
// .then((result) => console.log(result))
// .catch((err) => {
// console.log(err);
// });
// // 1
// // 2
// [1, 2][
// // 2
// // 1
// (2, 1)
// ];
// getForm
function getForm(e) {
e.preventDefault();
const form = document.getElementByName("getForm");
const formData = new formData(form);
console.log(formData);
console(formData["Email"]);
console(formData["Email"]);
}
// __module__/axios
// API call
// response - List of products
const response = jest.resolve({
list: ['product1,', 'product1'],
});
// findElement throw error, async
// -- placeholder, text,
// findAllElements
// getElement , throw error, dom
// -- placeholder, text,
// getAllElements
// queryElement // obj doesn't throw error
// -- placeholder, text,
// queryAllElements // []
describe('Text Poduct list page', () => {
it('should render the page', () => {
});
it('list is rendered', () => {
expect(list.length).toBe()
})
});
// premitive
// object -> {
// key:value
// }, Array ->
interface ProductInfo {
id: number
}
type Product = null | string | ProductInfo
function (product: Product<T>) {
console.log(product);
}
function (product: Product) {
console.log(product);
}
function (product: Product) {
console.log(product);
}
// ts-node index.ts
// typescript.config
//
*/
/**
* ROUND 2 Questions
*
* A AA AAA standards
How to secure cookies
How to handle form submission, with radio group
Make promise call - race, any, all
Test async api call - mock api
Diff between get find query
How to call out live changes for accessibility
How to render live content in ssg
Monolithic repo
How to do use inheritance in scss
.count + .container meaning
Type script Generic type
Type script how to assign multiple types and define individual when accessing in function
How to export module in vanilla js and create classes and extend
How to export module
Best way to define form submission- submit or button event
what are the webvitals? Explain all the matrices you can improve.
How http2.0 is better than http1.0
How to create chunks using webpack
// Part1: https://medium.com/udemy-engineering/transforming-frontend-architecture-a-journey-from-monolith-to-micro-frontends-at-udemy-part-1-e0a9c19c47bf
// Part2: https://medium.com/udemy-engineering/transforming-frontend-architecture-a-journey-from-monolith-to-micro-frontends-at-udemy-part-2-c9bd7ede5f1c
// Part3: https://medium.com/udemy-engineering/transforming-frontend-architecture-a-journey-from-monolith-to-micro-frontends-at-udemy-part-3-2dfdd74ff913
First Contentful Paint (FCP):
Cumulative Layout Shift (CLS):
Time to First Byte (TTFB):
First Input Delay (FID):
Largest Contentful Paint (LCP):
DOM Interactive:
*/