Filtering customers state array based on array of ids in javascscript/react.
const activeCustomerIdSet = [3,4,9];
//customers is array of customer data in my case its array value is bit different, just to note.
const filteredActiveCustomersIds = Array.from(activeCustomerIdSet) || [];
let nonActiveCustomers = [];
let filterCustomer = [...customers];
if (filteredActiveCustomersIds.length) {
for (let cid of filteredActiveCustomersIds) {
filterCustomer = filterCustomer?.filter(cust => {
if (+cust?.value?.id !== cid) {
return cust;
}
});
}
nonActiveCustomers = [...nonActiveCustomers,
filterCustomer];
}
console.log({ filteredActiveCustomersIds, customers, nonActiveCustomers });
Here I would like to share with you a very handy and new innovative approach using ES6 Tag Literals template to ease of creating the base URL’s for use a single source of truth defined as library constants or utility code to refer as the single page application grows.
Let’s get hand dirty and mind free from hassle of maintaining and forming lines cluttered code and creating mess in many files as web application grows.
Hope you understand what I mean, developers get frustrated to follow the best practice as in tight project deadlines,
Heads up on I am currently using 2Factor.in endpoints in this post as I were using part of the project implementation, we will head in list out numbers as steps needs to follow for the quick implementation:
We will save API key and API base URL in env file, (hope you are aware were it will lies in your project code, basically it lies at the core level of project director with named and with extension exactly, .env
3. Next we need to import publicRuntimeConfig object in our constants(.js) file
import { publicRuntimeConfig } from "./env.settings";
I am importing from .env.settings files which is actually using nextjs getConfig method to export publicRuntimeConfig variable, I am skipping that step to show here, once you search for docs on next/config you will get an idea what we are doing here.
4. Main part here it comes in contants.js file:
export const f2param1 = (param) => param || 1234657890;
export const f2param2 = (param) => param || "myTemplateName-OTP";
export function tagTemplate2FactorAPI(strings, param1, param2) {
const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';
let str0 = strings[0] || ""; // "That "
let str1 = strings[1] || ""; // " is a "
let str2 = strings[2] || ""; // "."
// We can even return a string built using a template literal
return `${prefixBaseUrl}${str0}${param1 || ''}${str1}${param2 || ''}${str2}`;
}
export const factor2API_Endpoint = {
CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN`,
SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${f2param1()}/AUTOGEN/${f2param2()}`,
SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${f2param1()}/${f2param2()}`,
CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};
console.log(factor2API_Endpoint.SEND_OTP_SMS);
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE);
console.log(factor2API_Endpoint.SEND_VERIFY_SMS);
This is how the final code looks, but there is a catch in this code, just need to handle of passing the params dynamically to the constants property of the object, otherwise with the fixed 2 params in same file would do the trick.
Will share once I got the way of passing dynamic params values to object property in template literal invocation line.
—— Here I found it the other approach —- Edited: 00:44 (after few mins of publishing this post after above approach shared 🙂 )
export function tagTemplate2FactorAPI(strings, ...keys) {
const { SITE_2FACTORIN_API_BASE_URL, SITE_2FACTORIN_API_KEY } = publicRuntimeConfig;
const prefixBaseUrl = SITE_2FACTORIN_API_BASE_URL + SITE_2FACTORIN_API_KEY + '/';
return (function (...values) {
let dict = values[values.length - 1] || {};
let result = [strings[0]];
keys.forEach(function (key, i) {
let value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
result.unshift(prefixBaseUrl); //added this line to prefix with base url path
return result.join('');
});
}
export const factor2API_Endpoint = {
CHECK_OTP_SMS_BALANCE: `BAL/SMS`,
SEND_OTP_SMS: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN`,
SEND_OTP_SMS_TEMPLATE: tagTemplate2FactorAPI`SMS/${0}/AUTOGEN/${1}`,
SEND_VERIFY_SMS: tagTemplate2FactorAPI`SMS/VERIFY/${0}/${1}`,
CHECK_TRANS_SMS_BALANCE: `/ADDON_SERVICES/BAL/TRANSACTIONAL_SMS`,
SEND_TRANS_SMS: `/ADDON_SERVICES/SEND/TSMS`,
SEND_TRANS_SMS_DYNAMIC_TEMPLATE: `/ADDON_SERVICES/SEND/TSMS`,
};
console.log(factor2API_Endpoint.SEND_OTP_SMS(12311312, 'newTemplate-newOTP'));
console.log(factor2API_Endpoint.SEND_OTP_SMS_TEMPLATE(5656565, 'newTemplate-newOTP'));
console.log(factor2API_Endpoint.SEND_VERIFY_SMS(456646545, 'newTemplate-newOTP'));
Here is the quick solution I found and worked for me, hope it helps you too in some scenario we might mistaking
As in the (a) was getting null as a data response in the react child component (where the text shown “Reset linked expired…”) , where actually data was updating from parent component and passed to react child component named <ResetPasswordForm … /> as ‘data’ as a prop, here its full code look like:
Solution 1 : To fix the issue of null, I have to remove the wrapping GlobalCookieContextProvider component as I was not passing any prop to it and also I have no use in this Reset Password Main component, so after removing the wrapping Provider component it worked like as expected, Boom!.
Results of JSON output attached to the form
Hence start receiving data from parent react component when state change updated dynamically from URL query params as expected.
But wait, Solution 1, was not working still as expected in certain refreshes, then work around did and moved the all query params check code from nextjs page component to its child level component named ResetPasswordForm component and everything finally working as expected again.
Hope you enjoyed the post, let me know in comments if confused you, will try to re-try to post again.
Happy we learning!
Conclusion
First found the wrapping un-used React Provider component, causing a stop of re-ending of react child component when parent component state update done, but after some further testing its was still breaking, final solution found in moving the router query params check and updating state into the first level child component itself which does the expected checks in useEffect() and render the component fairly with the expected results on query fetch done.
λ npm run dev
> developfe-dev@1.0.0 dev
> next
ready - started server on 0.0.0.0:3000, url: http://localhost:3000
info - Loaded env from F:\windows\developapp\code\.env
info - Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5
error - ./node_modules/@apollo/client/cache/core/cache.js:1:0
Module not found: Can't resolve 'optimism'
Import trace for requested module:
./node_modules\@apollo\client\cache\index.js
./node_modules\@apollo\client\core\index.js
./node_modules\@apollo\client\index.js
./pages\_app.js
https://nextjs.org/docs/messages/module-not-found
Terminate batch job (Y/N)?
^C
Next reinstalled package
F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0)
λ npm i @apollo/client@latest --save
added 9 packages, changed 1 package, and audited 1119 packages in 13s
90 packages are looking for funding
run `npm fund` for details
6 vulnerabilities (4 low, 2 high)
To address issues that do not require attention, run:
npm audit fix
Some issues need review, and may require choosing
a different dependency.
Run `npm audit` for details.
Then run again! boom!
F:\windows\developapp\code (main -> origin) (developfe-dev@1.0.0) λ npm run dev
> developfe-dev@1.0.0 dev > next
ready – started server on 0.0.0.0:3000, url: http://localhost:3000 info – Loaded env from F:\windows\developapp\code\.env info – Using webpack 5. Reason: Enabled by default https://nextjs.org/docs/messages/webpack5 event – compiled successfully
Hello, welcome and thanks to visit here to read my this short random post.
I was looking to take a random angular quiz to test my ability on Angular after a year around how much I remember about it, as because currently I mostly working with React and GraphQl, ApolloServer and Client and loving NextJS.
So after searching on Google, I landed up over this blog (here) (not an intention to use the link wrongly here), I took the Quiz and here is my result below with the image.
I too read some articles in the morning and look for tips and tricks on Angular so I can heads up well for the next interview on Angular 🙂
So I tried Quiz from the above blog link and here it is:
Question ah? How it could prove its my result, you can check on the full screenshot from my computer currently and tiny image up on the top corner and below on the Task bar with Chrome Active.
That’s all I would like to share with you all.
Thanks for reading and visiting. Have a great time and year’s ahead!
P.S. yes I forgot to mention, I am next going to take up more quiz and sharp my Angular blade more finer as possible as to be! Happy Learnings!
Stumble upon in the search of adding Buy me coffee script into react application land to the following wonderful hook solution to add script to react on stack overflow here
I will also add up here the update code of stack overflow which helped in the solution (for incase above shared link will be changed in future, and all the code credit is to the author of stack overflow user)
Update:
Now that we have hooks, a better approach might be to use useEffect like so:
useEffect(() => {
const script = document.createElement('script');
script.src = "https://use.typekit.net/foobar.js";
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, []);
Which makes it a great candidate for a custom hook (eg: hooks/useScript.js):
import { useEffect } from 'react';
const useScript = url => {
useEffect(() => {
const script = document.createElement('script');
script.src = url;
script.async = true;
document.body.appendChild(script);
return () => {
document.body.removeChild(script);
}
}, [url]);
};
export default useScript;
Which can be used like so:
import useScript from 'hooks/useScript';
const MyComponent = props => {
useScript('https://use.typekit.net/foobar.js');
// rest of your component
}
Solution, I have added on top a ‘config’ param to the useScript function for easy BMC Buy me coffee widget attributes to get added to script object dynamically:
Okay, well I was also looking for solution to this and here it is:
Mutation example of adding employee using Graphql Playground, most important step after you have added the code below to playground tab window:
# Write your query or mutation here
mutation AddEmployee(
$name: String!,
$phoneNumber: String!,
$email: String! ,
$designation: String,
$image: String) {
addEmployee(employee:
{ name: $name, phoneNumber:$phoneNumber, email: $email, designation: $designation, image:$image },
)
{
emp_id
name
}
}
You need to add your JSON payload to QUERY VARIABLES tab window (which is closed by default on below main playground window, without this input payload you will not see results, but error. (keep an eye on here while you make mutation test in graphql playground)