IT |
ITmedia 総合記事一覧 |
[ITmedia ビジネスオンライン] セブン-イレブンなどで「飯田商店 しょうゆらぁ麺」発売 人気ラーメン店の味をカップ麺で再現 |
https://www.itmedia.co.jp/business/articles/2205/19/news181.html
|
itmedia |
2022-05-19 20:51:00 |
IT |
ITmedia 総合記事一覧 |
[ITmedia PC USER] MicrosoftがWindows 11を「広範な展開」に指定 |
https://www.itmedia.co.jp/pcuser/articles/2205/19/news197.html
|
broaddeployment |
2022-05-19 20:30:00 |
AWS |
AWS Startups Blog |
A Startup’s Guide to AWS Services Series 3: Speeding Toward an MVP |
https://aws.amazon.com/blogs/startups/a-startups-guide-to-aws-services-series-3-speeding-toward-an-mvp/
|
A Startup s Guide to AWS Services Series Speeding Toward an MVPRunning a business is hard work with a lot of moving parts Startup founders have had to build deploy secure scale manage and monitor their software products all while controlling operational costs This installment of The Startup Guide to AWS Services video series matches services to situations to streamline the development process to develop and deploy an MVP fast |
2022-05-19 11:30:00 |
技術ブログ |
Developers.IO |
[레포트] Amazon EC2의 AMD 프로세서 기반 인스턴스를 통한 성능 및 총 소요 비용 최적화 |
https://dev.classmethod.jp/articles/optimize-performance-and-total-cost-with-amd-processor-based-instances-of-amazon-ec2/
|
레포트 Amazon EC의AMD 프로세서기반인스턴스를통한성능및총소요비용최적화안녕하세요클래스메소드김재욱 Kim Jaewook 입니다 이번에는AWS Partner Summit Korea 세션중「Amazon EC의AMD 프로세서기반인스턴스를통한성능 |
2022-05-19 11:06:02 |
海外TECH |
MakeUseOf |
5 Ways to Fix a Stuck Pixel on Your Screen |
https://www.makeuseof.com/tag/best-software-solutions-to-fix-a-stuck-pixel-on-your-lcd-monitor/
|
pixels |
2022-05-19 11:41:54 |
海外TECH |
DEV Community |
Angular, AWS Amplify manage mutiple environment diff based backend in easy way |
https://dev.to/sefatanam/angular-aws-amplify-manage-mutiple-environment-diff-based-backend-in-easy-way-38c1
|
Angular AWS Amplify manage mutiple environment diff based backend in easy wayHi Today I going to discuss about how you can manage multiple environment in AWS Amplify amp obiously diff based backend What does diff based backend mean In simple way Let say You start developing a application in dev branch initially and you entried many dummy data and also have dummy user credential for test purpose but now you want to deploy a fresh build into prestage mode this app Now how you do that This is the agenda for today Let s jump into it Technology that I am using Angular AWS AmplifyInitial Senario I suppose you do it well in dev with the aws amplify setup and rest of the things like Add GraphQL api completing CURD user Authentication using AWS Amplify auth components also dev deployment Now you stuck into how you can build a fresh build into a fresh environment without the dev s branch dummy data If you are beginner I m sure that you are frastrated that you can t get solution also after reading the docs No worries Here the steps you can go through StepCheck the environment status first amplify status you can saw current environment is set to devHere you can note down the GraphQL api endpoint and API KEY just for later check purpose note If you tried before to create environment before for the same project you can check that s are created or not via the amplify env list StepOnce you sure about the which environment you are then you need to create a new environment in aws amplify it will be better if you checkoutgit branch with a fresh copy of dev becaue if any thing goes wrong you can start again from the stage you are going to be start now run command amplify init it will ask you several questions Answer as follow Do you want to use an existing environment NoEnter name for the environment TYPE YOUR ENV NAME HERESelect the authentication method you want to use AWS profile But you can choose another Choose the profile you want to use SELECT CURRENT USED PROFILEThen you gonna see Your project has been successfully initialized and connected to the cloud StepNow try to add api amplify add api you gonna see soon that ampilfy tell you to go with the update command which is amplify update apiRun amplify update api then it will show you some default pre setuped information amp ask you some question to answer You can answer these as bellow Select a setting to edit Authorization modesChoose the default authorization type for the API YOUR CHOOICEEnter a description for the API KEY ENTER THE GRAPHQL API KEY that you saved earlier After how many days from now the api key should expire YOUR CHOOICEConfigure additional auth types YOUR CHOOICENow run amplify status you can see that all the operations now are in create mode That s mean you are almost done ┌ー┬ー┬ー┬ー┐│Category │Resource name │Operation │Provider plugin │├ー┼ー┼ー┼ー┤│Auth │ampytea │Create │awscloudformation │├ー┼ー┼ー┼ー┤│Hosting │amplifyhosting │Create │awscloudformation │├ー┼ー┼ー┼ー┤│Api │ampyt │Create │awscloudformation │└ー┴ー┴ー┴ー┘ all the operation are in create mode now run amplify push it will give an new GraphQL API endpoint and API KEY or you can check it after amplify push then you will able to see the same key it will given You have to remember that that s key only for the new environment that you created now not for another environment StepNote This is crusal part of this blog if you failed here you cant able to do diff based backend So try to understand step in cool mind now you have to checkout one more time via amplify env checkout ENV NAME after checkout update the API via amplify update api rest of the things are same as step but here you just need to put this API KEY which you got earlier when you push new environment into cloud the GraphQL API KEY Just paste it there and go on StepNow push it into cloud by amplify pushDeploy the frontend amplify publishCheck it out that is it works or not If in some end point you got access denied error you can check this solution |
2022-05-19 11:23:06 |
海外TECH |
DEV Community |
Create an Open Source Ecommerce Marketplace Part 2: Vender-Specific Orders |
https://dev.to/medusajs/create-an-open-source-ecommerce-marketplace-part-2-vender-specific-orders-1m80
|
Create an Open Source Ecommerce Marketplace Part Vender Specific OrdersIn the first part of this series you learned about Medusa Extender and how to use it to create a marketplace ecommerce platform The first part demonstrated how to link stores to users so that each new user has their own store then how to link products to a store so that the user can see and manage only their products In this part you ll learn how to link orders to their respective stores This will cover use cases where a customer purchases products from multiple stores and how to manage the overall status of that order You can find the full code for this tutorial in this GitHub repository You can alternatively use the Medusa Marketplace plugin as indicated in the README of the GitHub repository If you re already using it make sure to update to the latest version npm install medusa marketplace latest PrerequisitesIt is assumed that you ve followed along with the first part of the series before continuing this part If you haven t please start from there If you don t have the Medusa Admin installed it is recommended that you install it so that you can easily view products and orders among other functionalities Alternatively you can use Medusa s Admin APIs to access the data on your server However the rest of the tutorial will mostly showcase features through the Medusa Admin To add products with images you also need a file service plugin like MinIO installed on your Medusa server You can also check the documentation for more options for a file service This tutorial additionally makes use of the Next js starter storefront to showcase placing orders This is also optional and you are free to use other storefronts or Medusa s Storefront APIs instead Finally this part uses version of the Medusa Extender which introduced new features and a better developer experience If you have an old version of the Medusa Extender installed update the extender on your Medusa server npm install medusa extender Change the content of tsconfig json to the following compilerOptions module CommonJS declaration true emitDecoratorMetadata true experimentalDecorators true allowSyntheticDefaultImports true moduleResolution node target es sourceMap true skipLibCheck true allowJs true outDir dist rootDir src esModuleInterop true include src exclude dist node modules spec ts medusa config js And change scripts in package json to the following scripts seed medusa seed f data seed json build rm rf dist amp amp node modules bin tsc p tsconfig json start npm run build amp amp NODE ENV development node dist main js typeorm node require ts node register node modules typeorm cli js start watch nodemon watch src ts exec ts node src main ts start prod npm run build amp amp NODE ENV production node dist main What You Will Be BuildingAs mentioned in the introduction this part of the series will guide you through linking orders to stores To do that you ll override the Order model to add the relation between it and the Store model In a marketplace customers should be able to purchase products from multiple vendors at the same time So you ll also add a subscriber that when an order is placed will create “child orders Child orders will be linked to a store will only have products from the original order that belongs to that store and will be linked to the parent order For that reason you ll also add a parent child relation between Order models This relation will additionally let you manage the parent order s status based on the statuses of child orders Moreover you ll add a filter that ensures when a user retrieves the list of orders in their store only orders that belong to their store are retrieved This will also allow a super admin who does not belong to any store to track the parent orders Add Relations to the Order ModelThe first step is adding the relation between the Order and Store model and between Order models To do that you need to override the Order model Create a new directory src modules order which will hold all order related classes that you create throughout this tutorial Then create the file src modules order order entity ts with the following content import Column Entity Index JoinColumn ManyToOne OneToMany from typeorm import Entity as MedusaEntity from medusa extender import Order as MedusaOrder from medusajs medusa import Store from store entities store entity MedusaEntity override MedusaOrder Entity export class Order extends MedusaOrder Index Column nullable true store id string Index Column nullable false order parent id string ManyToOne gt Store store gt store orders JoinColumn name store id store Store ManyToOne gt Order order gt order children JoinColumn name order parent id parent Order OneToMany gt Order order gt order parent JoinColumn name id referencedColumnName order parent id children Order You add the model Order which overrides and extends Medusa s Order model In this model you add new columns store id and order parent id The store id column will be used for the many to one relation between the Order model and Store model which you demonstrate through the store property The order parent id column will be used for the many to one and one to many relation between Order models This leads to parent and children properties resulting from these relations Next in src modules store entities store entity ts add a new import for the Order model at the beginning of the file import Order from order order entity And inside the Store class add the relation to the Order model OneToMany gt Order order gt order store JoinColumn name id referencedColumnName store id orders Order Add a New MigrationTo reflect the new columns in the database you need to create a migration file in the order module As migration files have the format lt timestamp gt order migration ts a migration file is unique to you so you need to create it yourself Luckily the new update of Medusa Extender added a lot of helpful CLI commands to make redundant tasks easier for you You can generate the migration file using the following command node modules bin medex g mi orderThis will create the file src modules order lt timestamp gt order migration ts for you Open that file and replace the up and down methods with the following implementation public async up queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public order ADD COLUMN IF NOT EXISTS store id text ALTER TABLE public order ADD COLUMN IF NOT EXISTS order parent id text ALTER TABLE public order ADD CONSTRAINT FK addeecaddfcccbf FOREIGN KEY order parent id REFERENCES order id ON DELETE CASCADE ON UPDATE CASCADE await queryRunner query query public async down queryRunner QueryRunner Promise lt void gt const query ALTER TABLE public order DROP COLUMN store id ALTER TABLE public order DROP COLUMN order parent id ALTER TABLE public order DROP FOREIGN KEY FK addeecaddfcccbfcb await queryRunner query query The up method adds the columns store id and order parent id to the order table with a foreign key and the down method removes those columns and foreign key from the order table Run MigrationsPart of the Medusa Extender new CLI commands is the migrate command id command migrate reference which looks inside the src and dist directories for both files ending with migration js and JavaScript files inside a migrations sub directory of the directories You can refer to the Medusa Marketplace plugin to learn how you can run migrations from it Then if the migrations inside those files haven t been run before it runs or show them based on the option you pass to the command As the migration file you ve created is a TypeScript file you need to transpile it to JavaScript first before migrating the changes So run the following command npm run buildThis will transpile all TypeScript files inside the src directory into JavaScript files inside the dist directory Finally run the migration with the following command node modules bin medex migrate runIf you get an error about duplicate migrations because of migrations from the previous part of this series go ahead and remove the old ones from the dist directory and try running the command again If you check your database once the migration is run successfully you can see that the new columns have been added to the order table Override OrderRepositorySince you ve overridden the Order model you should override OrderRepository to make sure that when an order is retrieved the overridden model is used Create the file src modules order order repository ts with the following content import Repository as MedusaRepository Utils from medusa extender import EntityRepository from typeorm import OrderRepository as MedusaOrderRepository from medusajs medusa dist repositories order import Order from order entity MedusaRepository override MedusaOrderRepository EntityRepository Order export class OrderRepository extends Utils repositoryMixin lt Order MedusaOrderRepository gt MedusaOrderRepository List Orders By StoreIn this section you ll retrieve orders based on the store of the currently logged in user Modify LoggedInUserMiddlewareIn the previous part you created a middleware LoggedInUserMiddleware which checks if a user is logged in and registers them in the scope This allows you to access the logged in user from services and subscribers and this was used to retrieve products based on the logged in user s store However the previous implementation affects both storefront and admin routes in Medusa This can cause inconsistencies for customers accessing the storefront To ensure that the logged in user is only added to the scope for admin routes change the code in src modules user middlewares loggedInUser middleware ts to the following content import MedusaAuthenticatedRequest MedusaMiddleware Middleware from medusa extender import NextFunction Response from express import UserService from services user service Middleware requireAuth true routes method all path export class LoggedInUserMiddleware implements MedusaMiddleware public async consume req MedusaAuthenticatedRequest res Response next NextFunction Promise lt void gt let loggedInUser null if req user amp amp req user userId amp amp admin test req originalUrl const userService req scope resolve userService as UserService loggedInUser await userService retrieve req user userId select id store id req scope register loggedInUser resolve gt loggedInUser next The new change adds a new condition to check if the current route starts with admin If it does and if the user is logged in the logged in user is added to the scope Otherwise the value of loggedInUser in the scope will be null Although you can specify the path of the middleware to be admin to register this middleware for admin routes only this approach is necessary because if the loggedInUser is not registered in the scope an error will be thrown in any service or subscriber that uses it Override the OrderServiceThe Medusa server uses the method buildQuery in OrderService to build the query necessary to retrieve the orders from the database You ll be overriding the OrderService and particularly the buildQuery method to add a selector condition for the store id if there is a currently logged in user that has a store Create the file src modules order service ts with the following content import EntityManager from typeorm import OrderService as MedusaOrderService from medusajs medusa dist services import OrderRepository from order repository import Service from medusa extender import User from user entities user entity type InjectedDependencies manager EntityManager orderRepository typeof OrderRepository customerService any paymentProviderService any shippingOptionService any shippingProfileService any discountService any fulfillmentProviderService any fulfillmentService any lineItemService any totalsService any regionService any cartService any addressRepository any giftCardService any draftOrderService any inventoryService any eventBusService any loggedInUser User orderService OrderService Service scope SCOPED override MedusaOrderService export class OrderService extends MedusaOrderService private readonly manager EntityManager private readonly container InjectedDependencies constructor container InjectedDependencies super container this manager container manager this container container buildQuery selector object config relations string select string object if this container loggedInUser amp amp this container loggedInUser store id selector store id this container loggedInUser store id config select push store id config relations config relations config relations push children parent store return super buildQuery selector config Inside buildQuery you first check if there is a logged in user and if that user has a store If true you add to the selector parameter which is used to filter out data from the database a new property store id and set its value to the store ID of the logged in user You also add to the selected fields store id and you add the children parent and store relations to be retrieved along with the order Create the Order ModuleThe last thing before you can test out the changes you ve just made is you need to create an order module that imports those new classes you created into Medusa Create the file src modules order order module ts with the following content import Module from medusa extender import Order from order entity import OrderMigration from order migration import OrderRepository from order repository import OrderService from order service import OrderSubscriber from order subscriber Module imports Order OrderRepository OrderService OrderMigration export class OrderModule Please notice that you need to change the import and class name of the migration class based on your migration s name Then import this new module at the beginning of the file src main ts import OrderModule from modules order order module And inside the array passed to the load method pass the OrderModule await new Medusa dirname expressInstance load UserModule ProductModule OrderModule StoreModule Test it OutTo test it out start the server with the following command npm startThis will start the server on port Then start your Medusa admin and log in with the user you created in the first part of the series You should see on the orders page that there are no orders for this user If you re using Medusa s APIs you can view the orders by sending a GET request to localhost admin orders Handle Order Place EventIn this section you ll add a subscriber to handle the order placed event that is triggered whenever a new order is placed by a customer As mentioned earlier in the tutorial you ll use this handler to create child orders for each store that the customer purchased products from in their order Create a new file src modules order order subscriber ts with the following content import EventBusService OrderService from medusajs medusa dist services import LineItem OrderStatus from medusajs medusa import EntityManager from typeorm import LineItemRepository from medusajs medusa dist repositories line item import Order from order entity import OrderRepository from order repository import PaymentRepository from medusajs medusa dist repositories payment import Product from product entities product entity import ProductService from product services product service import ShippingMethodRepository from medusajs medusa dist repositories shipping method import Subscriber from medusa extender type InjectedDependencies eventBusService EventBusService orderService OrderService orderRepository typeof OrderRepository productService ProductService manager EntityManager lineItemRepository typeof LineItemRepository shippingMethodRepository typeof ShippingMethodRepository paymentRepository typeof PaymentRepository Subscriber export class OrderSubscriber private readonly manager EntityManager private readonly eventBusService EventBusService private readonly orderService OrderService private readonly orderRepository typeof OrderRepository private readonly productService ProductService private readonly lineItemRepository typeof LineItemRepository private readonly shippingMethodRepository typeof ShippingMethodRepository constructor eventBusService orderService orderRepository productService manager lineItemRepository shippingMethodRepository paymentRepository InjectedDependencies this eventBusService eventBusService this orderService orderService this orderRepository orderRepository this productService productService this manager manager this lineItemRepository lineItemRepository this shippingMethodRepository shippingMethodRepository this eventBusService subscribe OrderService Events PLACED this handleOrderPlaced bind this private async handleOrderPlaced id id string Promise lt void gt create child orders retrieve order const order Order await this orderService retrieve id relations items items variant cart shipping methods payments group items by store id const groupedItems for const item of order items const product Product await this productService retrieve item variant product id select store id const store id product store id if store id continue if groupedItems hasOwnProperty store id groupedItems store id groupedItems store id push item const orderRepo this manager getCustomRepository this orderRepository const lineItemRepo this manager getCustomRepository this lineItemRepository const shippingMethodRepo this manager getCustomRepository this shippingMethodRepository for const store id in groupedItems create order const childOrder orderRepo create order order parent id id store id store id cart id null cart null id null shipping methods as Order const orderResult await orderRepo save childOrder create shipping methods for const shippingMethod of order shipping methods const newShippingMethod shippingMethodRepo create shippingMethod id null cart id null cart null order id orderResult id await shippingMethodRepo save newShippingMethod create line items const items LineItem groupedItems store id for const item of items const newItem lineItemRepo create item id null order id orderResult id cart id null await lineItemRepo save newItem Here s a summary of this code In the constructor you register the method handleOrderPlaced as a handler for the event order placed Inside handleOrderPlaced you first retrieve the order using the ID passed to the method with the necessary relations for the creation of child orders You then loop over the items purchased in the order and group then inside the object groupedItems with the key being the unique store IDs and the value being an array of items You then loop over the keys in groupedItems and create a childOrder for each store The child orders have the same data as the parent order but they have parent id set to the ID of the parent order and store id set to the ID of the store it s associated with For each child order you need to create shippingMethods that are identical to the shipping methods of the parent order but associated with the child order For each child order you need to add the items that were in the order for that specific store as each vendor should only see the items ordered from their store Make sure you have Redis installed and configured with Medusa for this subscriber to work Test it OutTo test it out first restart your Medusa server then run the storefront that you re using for your store and add one of the products you created for a vendor to the cart then place an order If you then open the admin panel again and check orders you should see a new order on the orders page of the vendor If you open it you ll see details related to the order Try creating more users and adding products for different users and stores You ll see that each user will see the order with items only related to their store Handle Order Status Changed EventsTo ensure that the status of the parent order changes as necessary with the change of status of the child orders it s necessary to listen to the events triggered whenever an order s status changes In the constructor of the OrderSubscriber class in src modules order order subscriber ts add the following code add handler for different status changesthis eventBusService subscribe OrderService Events CANCELED this checkStatus bind this this eventBusService subscribe OrderService Events UPDATED this checkStatus bind this this eventBusService subscribe OrderService Events COMPLETED this checkStatus bind this This adds the same method checkStatus as the order handler of the events Canceled Updated and Completed of an order Next add inside the class the following methods public async checkStatus id id string Promise lt void gt retrieve order const order Order await this orderService retrieve id if order order parent id retrieve parent const orderRepo this manager getCustomRepository this orderRepository const parentOrder await this orderService retrieve order order parent id relations children const newStatus this getStatusFromChildren parentOrder if newStatus parentOrder status switch newStatus case OrderStatus CANCELED this orderService cancel parentOrder id break case OrderStatus ARCHIVED this orderService archive parentOrder id break case OrderStatus COMPLETED this orderService completeOrder parentOrder id break default parentOrder status newStatus parentOrder fulfillment status newStatus parentOrder payment status newStatus await orderRepo save parentOrder public getStatusFromChildren order Order string if order children return order status collect all statuses let statuses order children map child gt child status remove duplicate statuses statuses new Set statuses if statuses length return statuses remove archived and canceled orders statuses statuses filter status gt status OrderStatus CANCELED amp amp status OrderStatus ARCHIVED if statuses length all child orders are archived or canceled return OrderStatus CANCELED if statuses length return statuses check if any order requires action const hasRequiresAction statuses some status gt status OrderStatus REQUIRES ACTION if hasRequiresAction return OrderStatus REQUIRES ACTION since more than one status is left and we filtered out canceled archived and requires action statuses only pending and complete left So return pending return OrderStatus PENDING Here s a summary of the code snippet In checkStatus you first retrieve the order s data using its ID You check if the order has a parent order This is to avoid handling events triggered for the parent order as it is not necessary You then retrieve the parent order with its relation to its children orders You make use of another method getStatusFromChildren to deduce the status of the parent order from the children You first retrieve all statuses from the child orders then remove any duplicates If the result of removing the duplicates leads to only one status then it means that all orders have the same status and the parent can have that same status as well Otherwise if there s more than one status you remove the archived and canceled orders If this leads to no statuses this means that all children are either canceled or archived and the parent should have the same status The code snippet defaults to the “canceled status here but you can change that Otherwise if there s only status left after removing canceled and archived orders you return that status Otherwise if there s more than one status left you check if one of those statuses is requires action and return that as the status If there s no requires action status you can infer there are only pending and complete orders left Since it s logical to consider that if at least one order is pending then you can consider the parent order pending you default to that status After retrieving the deduced status of the parent order if that status is different than the current status of the parent order you update its status Depending on the new status you either use existing methods in the OrderService to update the status or manually set the status in the order Test it OutRestart your Medusa server Then open the Medusa admin to the order you just created earlier Try canceling the order by clicking on the top dots then clicking “Cancel Order After canceling the order log out and log in with a super admin user By default the super admin user is the user created when you seed the database at the beginning of your Medusa server set up This user has the email “admin medusa test com and password “supersecret If you open the parent order you ll see that it s now canceled as well ConclusionBy following those parts you should now have stores for each user with products and orders linked to them In the next part of the series you ll learn about how to add more than one user to a store how to add super admins and how to customize other settings Should you have any issues or questions related to Medusa then feel free to reach out to the Medusa team via Discord |
2022-05-19 11:20:17 |
海外TECH |
DEV Community |
React Hooks Best Practices in 2022 |
https://dev.to/kuldeeptarapara/react-hooks-best-practices-in-2022-4bh0
|
React Hooks Best Practices in Class based components previously had access to React capabilities like state and lifecycle functions For this reason function based components are called “thin or purely presentational since they cannot access state and lifecycle functions Since React Hooks was released function based components have become first class citizens of React Moreover some companies offering services in React development Also they provide dedicated React developers for hiring who can help throughout your development journey New methods to compose reuse and share React code has been made possible thanks to function components Simple Example of Hookimport React useState from react function Example Declare a new state variable which we ll call count const count setCount useState return lt div gt You clicked count times lt button gt setCount count amp gt Click me lt button gt lt div gt Output After Clicking You Will Get Output Like Below In this piece we will provide you with six strategies for using React Hooks in your components Hooks Regulations Should Be FollowedAlthough it may seem self evident both novice and experienced React developers often fail to observe the following guidelines when using React hooks A Call Hooks at the Highest LevelKeep hooks out of loops nested functions and conditions Inside the hooks add the conditions you wish to apply to your application This should not be done if name useEffect function persistForm localStorage setItem formData name Instead do this useEffect function persistForm if name localStorage setItem formData name All Hooks will be called sequentially when a component is rendered thanks to this rule React is able to do this because of the useState and use effect functions that enable the state of Hooks to be preserved appropriately B Only Call Hooks from Function ComponentsRegular JavaScript functions should not invoke hooks Function components or custom hooks may only be used to call hooks in an application This rule ensures that every stateful logic in a component may be easily seen in the source code by following this rule React hooks may benefit from the ESLint pluginAn ESLint plugin for React Hooks has been developed by the React team and is known as eslint plugin react Before you ever start to execute your application this plugin will detect and correct hooks issues It has simples rules react hooks rules of hooksreact hooks exhaustive depsThe first rule simply compels your code to comply with the requirements of hooks To ensure that the useEffect s rule is being adhered to exhaustive deps is employed Exhaustive deps warnings may be triggered by the following userInfo component because the useEffect uses the userId variable but it doesn t appear in the dependencies arrayReact hooks rules of hooks function Form Use the accountName state variableconst accountName setAccountName useState David Use an effect for persisting the formuseEffect function persistForm localStorage setItem formData accountName Use the accountDetail state variableconst accountDetail setAccountDetail useState Active Use an effect for updating the titleuseEffect function updateStatus document title accountName accountDetail React hooks exhaustive deps import React useState from react import ReactDOM from react dom function Account props const name setName useState David return Hello name The price is props total and the total amount is props amount ReactDOM render document getElementById root Building function components in order is crucial To get the most out of your React application it s important to follow specific rules while creating class components Once you ve called the function Object native code and started your state you re ready to go The component s job related functions come next followed by the lifecycle functions When you re done you ll need tocreate the render method import React useState from react const propTypes id propTypes number isRequired url propTypes string isRequired text propTypes string const defaultProps text Hello World class Link extends React Component static methodsAreOk return true constructor props super props this state user null componentDidMount console log component did mount componentDidUpdate console log component did update componentWillUnmount console log component will unmount render return this props text Link propTypes propTypesLink defaultProps defaultPropsexport default Link A class component has a built in function Object native code and a lifecycle function however function components don t have these features function App const user setUser useState null useEffect amp gt console log component is mounted const name setName useState return lt h gt React component order lt h gt Like class components it s important to have a clear structure for your function components Once state variables have been declared and subscriptions have been set up any appropriate functions may then be written using useEffect hook Finally you should send back the rendered components to the browser function App const user setUser useState null const name setName useState useEffect amp gt console log component is mounted return lt h gt React component order lt h gt Your code will be easier to read and understand if you enforce a logical structure UseState works just as class component s stateDeclaring multiple variables for each state is common practice in many useState examples const name setName useState Liam Walker const email setEmail useState liamwalker email com const age setAge useState However useState is able to contain both arrays and objects It s still possible to arrange relevant information together such as in the following example const user setUser useState name Liam email liamwalker email com age There is however a catch When the useState update function is used to update the state the old state is removed and the new one is used instead This is not the same as the this of a class component new state is combined with old one in setStateconst user setUser useState name Liam email liamwalker email com age setUser name Lucas result name Lucas In order to maintain the prior state you need to merge it manually by implementing a callback function that sends the current state value into it Given that the user variable provided as state value in the preceding example the following argument may be sent to the setUser function setUser user amp gt user name Lucas result is name Lucas email liamwalker email com age Depending on how frequently your application s data changes it s a good idea to break state into multiple variables As a rule of thumb it s best to keep each state separate so that it s easy to update and submit the data Balance Several useState Requests With a Single Call to the APICustom hooks may be used to share functionality across applications Some of your application logic will be reused across multiple components as you create your programme Custom hooks allow you to separate your component s functionality into reusable functions as described in the next article which is about React Hooks You may publish your hooks to a single curated collection using Bit Github Using this method you may install and reuse them in many apps A new “hooks library project isn t necessary you can just “push new hooks from any project to your shared collection Hooks can t be used in class components which is the main drawback to this technique There are a few options if you still utilize old class components in your project you can either turn those components into functions or use alternative reusable logic patterns with HOC or Render Props Avoid prop drilling with usageConstantly passing data down from one parent component to another until it reaches the appropriate child component is known as context prop drilling in React applications Other nested components don t really require them It is possible to transfer data down via the component tree without having to manually provide props between components using React Context The useContext hook allows the child components to make use of the parent component s React Context property Conclusion This is a fantastic addition to the React framework allowing you to compose reuse and share React code in a manner that was before impossible New best practices for building React Hooks are required since Hooks alter the way developers construct React components in order to facilitate development and cooperation across numerous teams Thank you for reading our article Hope you enjoyed the article Please share your ideas with us and do let us know your questions we are always here to solve you problems Moreover Bosc Tech has a team of React experts Contact us for any need in React development Do let us know your queries |
2022-05-19 11:08:16 |
海外TECH |
DEV Community |
How to tell a Junior Dev that what they've done is wrong? |
https://dev.to/nombrekeff/how-to-tell-a-junior-dev-that-what-theyve-done-is-wrong-4igo
|
How to tell a Junior Dev that what they x ve done is wrong I struggle with this a lot how do you approach this How do you explain that what they ve done is wrong it affects the rest of the team and that they should think more about the problem and side effects Without affecting their confidence and morale too much by doing so I m always afraid of affecting them negatively What if the issue is recurrent and happens on most tasks they re assigned to Not too bad as to justify a layoff but enough to increase development times How do you deal and communicate these things Cheers Waiting for your helpful advice as always |
2022-05-19 11:00:56 |
Apple |
AppleInsider - Frontpage News |
Apple tech could create invisible input areas on bezels to replace buttons |
https://appleinsider.com/articles/22/02/01/apple-tech-could-create-invisible-input-areas-on-bezels-to-replace-buttons?utm_medium=rss
|
Apple tech could create invisible input areas on bezels to replace buttonsApple is continuing to develop technology that could allow virtually invisible input areas that can display information to a user while replacing physical buttons or controls on its products A figure from the patent depicting a MacBook Concealable input region for an electronic device is a newly revealed patent application describes technology that uses microperforations to sense input Read more |
2022-05-19 11:50:31 |
Apple |
AppleInsider - Frontpage News |
How to run MacOS 7 and MacOS 8 in your browser, today |
https://appleinsider.com/articles/22/04/01/how-to-run-macos-7-and-macos-8-in-your-browser-today?utm_medium=rss
|
How to run MacOS and MacOS in your browser todayStep back in time to the Macintosh of the s and run complete virtual installations of System and Mac OS in a browser window There is a single flaw in the new virtual versions of s Mac software and it s that they run at the speed of Macs in the s What you see is straight up Mac SE or Quadra but everything is as fast as Apple Silicon can make it You could do actual work in these simulated OSes they even come with the ability to drag documents or files in and out from macOS Monterey But whether it s for some practical purposes or more likely for the sheer fun of it here s how to do it Read more |
2022-05-19 11:43:49 |
Apple |
AppleInsider - Frontpage News |
Future Apple keyboard could have one key that can pop out and be used as a mouse |
https://appleinsider.com/articles/21/08/19/future-apple-keyboard-could-have-one-key-that-can-pop-out-and-be-used-as-a-mouse?utm_medium=rss
|
Future Apple keyboard could have one key that can pop out and be used as a mouseApple is continuing researching on how one key on the MacBook Pro keyboard could be taken out and used as a precision mouse A removable key that doubles as a mouse is not intended to replace the trackpad Deployable Key Mouse is a newly revealed patent application yet Apple must be serious about this idea because it was previously granted a near identical patent in March Read more |
2022-05-19 11:40:50 |
海外TECH |
Engadget |
Audi will integrate Apple Music into 'nearly all' of its newer models |
https://www.engadget.com/audi-integrate-apple-music-newer-models-114025901.html?src=rss
|
Audi will integrate Apple Music into x nearly all x of its newer modelsAudi owners can now play Apple Music through their infotainment systems without having to connect it to their iPhones via Bluetooth or USB The luxury automaker has rolled out Apple Music integration for almost all of its newer vehicles in Europe North America and Japan starting with the model year Even cars already on the road will get the feature through an automatic over the air update nbsp After getting the app on their infotainment systems Audi owners simply need to fire it up follow the onscreen instructions and type in the Apple ID login they use for Apple Music The system will send a verification code to their phones that they have to key in but that s pretty much it for the setup process In Europe owners can enjoy the first GB of streaming free of charge and will be billed the subsequent cellular data streaming costs through a data package available from Cubic Telekom nbsp Audi vehicles already come with Apple s CarPlay ーit started bundling the software with its European vehicles in and with its North American vehicles a year later Through CarPlay users can connect their phones to their infotainment systems to get directions optimized for traffic make calls send and receive messages and play Apple Music onscreen This standalone Apple Music rollout however makes it a lot easier to access their playlists and all the other available tracks on the service |
2022-05-19 11:40:25 |
海外TECH |
Engadget |
Apple's AirTag four-pack falls to $89 |
https://www.engadget.com/apples-air-tag-4-pack-falls-to-89-112542044.html?src=rss
|
Apple x s AirTag four pack falls to If you ve got a bunch of items you need to protect from theft or loss you can now pick up a four pack of Apple s AirTags at Amazon and Best Buy for or percent off We ve seen them a little bit cheaper recently but it s still a good time to act if you missed the last deal nbsp Buy Apple AirTags pack at Amazon Buy Apple AirTags pack at Best Buy For Apple users AirTags deliver significant advantages over Tile and other trackers The ultra wideband feature offers precise tracking with iPhone or later devices when you re reasonably close so you can narrow your search between a bed and night table in the same bedroom Over wider distances the Apple device AirTag networks lets you track down an object you might have misplaced in a bar for instance AirTags use a simple coin sized design and offer a seamless experience via the Find My app You can also force an AirTag to emit a chime to help you pinpoint an object s location and that chime is now loader than ever thanks to a recent update It does lack a built in keyring like rival trackers so you ll need to pay extra for that And it only works with Apple devices so Android users will need to look elsewhere However if you re in Apple s ecosystem you can pick up four at a discount ーjust remember that the deal ends today Follow EngadgetDeals on Twitter for the latest tech deals and buying advice |
2022-05-19 11:25:42 |
海外TECH |
Engadget |
The Morning After: New York City's Airbnb listings may outnumber rentable apartments |
https://www.engadget.com/the-morning-after-new-york-citys-airbnb-listings-may-outnumber-rentable-apartments-111529674.html?src=rss
|
The Morning After New York City x s Airbnb listings may outnumber rentable apartmentsAirbnb makes news for a mix of good and bad reasons When it s not expanding the service to make it easier to stay between multiple properties on the same trip its safety team and terrible rentals are becoming the subject of a documentary series Now according to a report from Curbed April apartment rental inventory in Manhattan Brooklyn and northwest Queens numbered units That compares to somewhere between and entire apartment or entire home Airbnb listings across all of NYC as calculated by AirDNA and Inside Airbnb New York City prohibited short term rentals less than days in multi unit buildings without the owner present since making it illegal to even advertise such listings in The report hasn t traced whether Airbnb hosts are following these guidelines Airbnb hasn t solely caused the NYC housing shortage an issue seen in most desirable cities across the world In New York rents are going up and permits for new apartments are down by “a double digit percentage said Airbnb s spokesperson However the optics of having more Airbnb listings than rentable apartments are not good Mat SmithThe biggest stories you might have missedIt s Cooking Week at Engadget A beginner s guide to smart sous videFacebook issues checks to Illinois residents as part of class action lawsuitApple faces AirPods lawsuit after an Amber Alert allegedly caused hearing damageAcer brings glasses free D to its gaming laptopsAcer unveils a pair of portable glasses free D monitorsHonda shows off its first electric SUV the PrologueApple s former machine learning director reportedly joins Google s DeepMind teamRussia claims it s using new laser weapons against UkraineThe technology reportedly blinds satellites and destroys drones Russia is reportedly testing out new technology on the battlefield as it continues its invasion of Ukraine According to a Reuters report the Russian government says it s using a new wave of laser weapons One weapon a destructive laser called Zadira can apparently burn up drones Deputy prime minister Yury Borisov said that in one test it incinerated a drone miles away within five seconds A more established system Peresvet reportedly blinds satellites up to miles above Earth Continue reading NASA will soon bid farewell to its Mars InSight landerThe lander is expected to end its science activities by the end of summer NASA NASA s Mars InSight lander will soon no longer be able to send back data and images It s been gradually losing power for a while now as dust continues to accumulate on its solar panels The darker skies expected in the next few months ーalso due to having more dust in the air ーwon t help either The space agency believes the lander will no longer be able to sustain its seismometer by the end of summer Continue reading Amazon refreshes its Fire tablets with faster CPUs and longer battery lifeThe new Fire will set you back at least The new Fire has double the RAM of the previous generation and is powered by a quad core processor that s percent faster It also has percent more battery life and can last for up to hours while browsing and watching videos Unlike previous Fire models it now comes with a USB C port instead of a micro USB One day I ll shut up about USB C I promise The Fire is available in black denim and rose and will set you back at least It will start shipping on June th and is available to preorder now Continue reading Homeland Security pauses disinformation board three weeks after creating itThe group s leader was the target of harassment and threats The Department of Homeland Security DHS has paused a Disinformation Governance Board just three weeks after its April th announcement Officials reportedly decided to shut down the board on May th but that decision appears to be on hold after a last minute effort to retain board leader Nina Jankowicz She resigned from the board and the DHS today May th Far right influencers and media outlets portrayed the board as a censorship tool and villainized Jankowicz The campaigns led to harassment and threats against the board leader Continue reading Sony s LinkBuds S are smaller noise canceling earbudsLots of new Sony headphones to pine after Sony Sony s LinkBuds S are apparently designed for a never off wearing experience with transparency mode allowing you to tune into your surroundings as needed Unlike the open ear LinkBuds that debuted earlier this year the LinkBuds S have a more traditional closed design with a shape that s more similar to Sony s flagship WF XM buds These however are much smaller The LinkBuds S are up for pre order now with general availability starting May th Continue reading |
2022-05-19 11:15:29 |
海外TECH |
CodeProject Latest Articles |
MathML to Plain Text Converter |
https://www.codeproject.com/Tips/5331794/MathML-to-Plain-Text-Converter
|
string |
2022-05-19 11:07:00 |
海外科学 |
NYT > Science |
Seeking Pills, Young People Head to Social Media, With Deadly Results |
https://www.nytimes.com/2022/05/19/health/pills-fentanyl-social-media.html
|
Seeking Pills Young People Head to Social Media With Deadly ResultsThe soaring drug fatalities in the U S are being fueled partly by fentanyl tainted pills bought by teenagers and young adults on Snapchat Instagram TikTok and other social media apps |
2022-05-19 11:55:59 |
ニュース |
@日本経済新聞 電子版 |
日用品市場で今、ツールの逆転が起きているのが制汗デオドラント。長年スプレータイプが主流でしたが、最近では直接肌に塗り込む「じか塗り」が主役に。「デオナチュレ」成功の背景を考えます。
#ヒットのクスリ
https://t.co/VoqcGb9u0z |
https://twitter.com/nikkei/statuses/1527257824128008192
|
日用品市場で今、ツールの逆転が起きているのが制汗デオドラント。 |
2022-05-19 12:00:15 |
ニュース |
@日本経済新聞 電子版 |
株・金利・原油、急変動を警戒 恐怖指数が各市場で上昇
https://t.co/O6jcQuLSTX |
https://twitter.com/nikkei/statuses/1527253156668661760
|
恐怖指数 |
2022-05-19 11:41:42 |
ニュース |
@日本経済新聞 電子版 |
韓国の大手企業で「賃上げドミノ」――。SKハイニックスやサムスン電子など高収益企業の若手社員が年功序列の賃金体系に不満の声。経営側への圧力になっています。
https://t.co/9I9dG61Zd2 |
https://twitter.com/nikkei/statuses/1527252756867821569
|
不満の声 |
2022-05-19 11:40:06 |
ニュース |
@日本経済新聞 電子版 |
小中高生に出前実験教室を開く傍ら、ユーグレナなど多くのスタートアップの創業や事業拡大を後押ししてきたリバネスCEOの丸幸弘さん。「『サイエンス』をわかりやすく伝え、社会に根付かせる」という使命感が原点にあります。… https://t.co/cuuV5BByx4 |
https://twitter.com/nikkei/statuses/1527246488392323073
|
|
2022-05-19 11:15:12 |
ニュース |
@日本経済新聞 電子版 |
日本の半導体「最後で最大のチャンス」JEITAが戦略提言
https://t.co/zoZZr8WqGG |
https://twitter.com/nikkei/statuses/1527245366332391424
|
jeita |
2022-05-19 11:10:44 |
ニュース |
@日本経済新聞 電子版 |
確定拠出年金、自身の運用で変わる受給額 税優遇も
https://t.co/wvNrYFubLs |
https://twitter.com/nikkei/statuses/1527244346533507072
|
確定拠出年金 |
2022-05-19 11:06:41 |
ニュース |
BBC News - Home |
Boris Johnson will not face a further Partygate fine, says No 10 |
https://www.bbc.co.uk/news/uk-politics-61508110?at_medium=RSS&at_campaign=KARANGA
|
lockdown |
2022-05-19 11:20:14 |
ニュース |
BBC News - Home |
EuroMillons: Lottery winners scooped £184m with lucky dip ticket |
https://www.bbc.co.uk/news/uk-england-gloucestershire-61495849?at_medium=RSS&at_campaign=KARANGA
|
record |
2022-05-19 11:19:28 |
ニュース |
BBC News - Home |
Bobbi-Anne McLeod: Man fascinated with serial killers murdered Plymouth teen |
https://www.bbc.co.uk/news/uk-england-devon-61506642?at_medium=RSS&at_campaign=KARANGA
|
bobbi |
2022-05-19 11:46:37 |
ニュース |
BBC News - Home |
Rebekah Vardy called highly unreliable witness by Coleen Rooney's lawyer |
https://www.bbc.co.uk/news/entertainment-arts-61506895?at_medium=RSS&at_campaign=KARANGA
|
court |
2022-05-19 11:50:30 |
ニュース |
BBC News - Home |
Pressure builds on Rishi Sunak to act now on living costs |
https://www.bbc.co.uk/news/business-61506985?at_medium=RSS&at_campaign=KARANGA
|
inflation |
2022-05-19 11:06:35 |
ニュース |
BBC News - Home |
Billy Sharp: Fan jailed for headbutting player at end of match |
https://www.bbc.co.uk/news/uk-england-nottinghamshire-61505835?at_medium=RSS&at_campaign=KARANGA
|
nottingham |
2022-05-19 11:46:10 |
ニュース |
BBC News - Home |
Platinum Jubilee: When's the bank holiday to mark the Queen's 70-year reign? |
https://www.bbc.co.uk/news/uk-61248636?at_medium=RSS&at_campaign=KARANGA
|
elizabeth |
2022-05-19 11:45:59 |
ビジネス |
不景気.com |
共済組合運営の「京都平安ホテル」が6月で休業、従業員解雇へ - 不景気com |
https://www.fukeiki.com/2022/05/kyoto-heian-hotel-close.html
|
京都市上京区 |
2022-05-19 11:39:26 |
北海道 |
北海道新聞 |
連合が立憲・国民の競合容認 参院選1人区巡り一本化不調 |
https://www.hokkaido-np.co.jp/article/682935/
|
連合 |
2022-05-19 20:10:04 |
GCP |
Cloud Blog |
Security Roundup - stories and launches from first quarter 2022 |
https://cloud.google.com/blog/topics/developers-practitioners/security-roundup-stories-and-launches-first-quarter-2022/
|
Security Roundup stories and launches from first quarter The security world keeps changing with new tools and new threats in the ever evolving arms race that is cybersecurity To keep you up to speed on all that Google Cloud is doing to help safeguard your data and your applications welcome to the first installment of the Security Roundup In this regular series I ll be sharing a selection of news and guidance to help ensure you have the resources you need for your hectic high stakes harm preventing job Applying the principle of least privilege to GKE clusters Access to your GKE clusters just like any other resource should be based on the principle of least privilege Use groups individual roles and Identity and Access Management tools to limit who can do what with your Kubernetes clusters in Google Cloud These principles can help you control who uses which elements of the Kubernetes API as well as how they access your clusters More details are in Anthony Bushong s video Ensuring CI CD pipeline securityTo make sure only trusted code artifacts enter your continuous integration and deployment pipeline you can take advantage of Binary Authorization on Google Cloud and then only permit signed builds to go through Learn more in Martin Omander s video interview and walkthrough with XIaowen Lin Protecting against denial of service and flooding attacksOnce your applications are on the web they become potential targets for attack You can use Cloud Armor to protect against many types of traffic attacks including distributed denial of service DDoS and HTTP POST flood attacks After learning the normal traffic patterns of your apps Cloud Armor monitors for anomalies and then generates alerts or intervenes on your behalf to block malicious traffic Learn more with Arman Rye in this video Defending against cyberattacks with Palo Alto NetworksIf you use Palo Alto Networks products for endpoint protection or network monitoring now you can integrate the signals from those systems into Google Cloud security tools You can ingest device health conclusions from Palo Alto Networks Cortex XDR to boost your visibility into those endpoints state and improve your trust decisions BeyondCorp Enterprise users can incorporate Cortex XDR metadata into access policies leveraging additional posture information to add another level of trusted device information and operate with more confidence Check out the details in this interview with Mason Yan at Palo Alto Networks Dealing with Apache Logj vulnerability ies Attackers who exploit the Apache Logj vulnerability can execute arbitrary code on a vulnerable server Read this post by the Google Cybersecurity Action Team for more details on logj vulnerabilities CVE and CVE and how you can find out if you re affected It includes advice for how to use Google Cloud products like Binary Authorization rules and Security Command Center to keep your cloud deployments safe Good luck out there and remember Keep your data yours Related ArticleIn case you missed it Google Cloud Security Talks Threat Detection amp Response EditionIn case you missed it join us for Google Cloud Security Talks focused on security operations and modernizing your approach to threat det Read Article |
2022-05-19 12:00:00 |
コメント
コメントを投稿