React Interview Questions

Replace array value in javascript

var users = [
{id: 1, firstname: 'John', lastname: 'Ken'},
{id: 2, firstname: 'Robin', lastname: 'Hood'},
{id: 3, firstname: 'William', lastname: 'Cook'}
];

var editedUser = {id: 2, firstname: 'Michael', lastname: 'Angelo'};

users = users.map(u => u.id !== editedUser.id ? u : editedUser);

console.log('users -> ', users);
Remove array value in javascript
let value = 3

let arr = [1, 2, 3, 4, 5, 3]

arr = arr.filter(item => item !== value)

console.log(arr)
// [ 1, 2, 4, 5 ]


Hooks in react

useState, useEffect, useRef, useMemo

When to use a Class Component over a Function Component?

If the component needs state or lifecycle methods then use class component otherwise use function component.

 What is Middleware?


arrow function vs normal function ?


What is the use of super(props) ?

So, the simple answer to this question is that this thing basically allows accessing this.props in a Constructor function. In fact, what the super() function does is, calls the constructor of the parent class. 



#async/await VS #Promises

Promises

const req = require("axios")
const getData = async () => {
  req
    .get("https://www.someapi/something")
    .then((resp) => {
      console.log("Resp : ", resp.data);    //Handling resolved case
    })
    .catch((error) => {
      console.log("Error : ", error);       //Handling rejection case
    });
};


getData();

Async/Await

const req = require("axios")
const getData = async () => {
  try {
    const resp = await req.get("https://www.someapi/something");
    console.log("Resp : ", resp.data);
  } catch (error) {
    console.log("Error : ", error);
  }
};


getData();
both Promises and Async/await are used to handle asynchronous code in JavaScript. Promises are a cleaner way to handle asynchronous code that allows for chaining .then() and .catch() methods, while Async/await provides a more procedural syntax that makes asynchronous code look similar to synchronous code, with better error handling capabilities.
Promises are objects that represent the eventual completion or failure of an asynchronous operation and provide a cleaner way to handle asynchronous code by chaining .then() and .catch() methods. The .then() method is used to handle successful responses, while the .catch() method is used to handle errors. 
Objects foreach
const newObj = {};

let obj = { a:1, b:2, c:3}

Object.keys(obj).forEach(function(key) {

    newObj[obj[key]] = key

});

// Object.entries(obj).map(([key,value],i) =>
Object.entries(obj).map(([key,value],i) =>
    // <option key={i} value={key}>{value}</option>
    newObj[value] = key
)  

console.warn(newObj);

OUTPUT: { '1': 'a', '2': 'b', '3': 'c' }

Comments

Popular posts from this blog

Simple Redux

Add Axios Interceptor in Services where Api is called