投稿時間:2023-08-19 22:06:11 RSSフィード2023-08-19 22:00 分まとめ(7件)
カテゴリー等 | サイト名等 | 記事タイトル・トレンドワード等 | リンクURL | 頻出ワード・要約等/検索ボリューム | 登録日 |
---|---|---|---|---|---|
python | Pythonタグが付けられた新着投稿 - Qiita | 【Python】辞書ネスト取得方法 | https://qiita.com/ayamo/items/87f92e76ee3c7988b0ac | 辞書 | 2023-08-19 21:48:28 |
海外TECH | MakeUseOf | How to Edit YouTube Videos for Free: 5 Options | https://www.makeuseof.com/how-to-edit-youtube-videos-for-free/ | editing | 2023-08-19 12:15:23 |
海外TECH | MakeUseOf | How to Enable or Disable Autoplay on Spotify | https://www.makeuseof.com/how-to-enable-disable-autoplay-spotify/ | spotify | 2023-08-19 12:01:23 |
海外TECH | DEV Community | Simplified Micro Front-Ends: Mastering Global State Management with Redux and Redux Toolkit | https://dev.to/serifcolakel/simplified-micro-front-ends-mastering-global-state-management-with-redux-and-redux-toolkit-4lan | Simplified Micro Front Ends Mastering Global State Management with Redux and Redux ToolkitProject RepositoryThis article based on this article I just added some extra features AuthorIn today s rapidly evolving world of web development embracing micro front end architecture has become a strategic imperative This article presents a comprehensive guide that navigates through the intricate landscape of micro front ends demonstrating how to seamlessly integrate Redux and Redux Toolkit to efficiently manage global states As we delve into the heart of this guide you ll embark on a journey to streamline your development process centralize state management and amplify user experiences By the end you ll possess the knowledge to effectively reshape your architecture yielding applications that are not only modular and scalable but also infused with the power of Redux driven state management ReduxToolkit and React Redux installationIn this section we will install redux and react redux Run the following command in the terminal referencenpm install reduxjs toolkit react redux Redux Store ConfigurationCreate a folder called store in the src folder and create a file called index ts inside it You can run the following command in the terminal to create the folder and file mkdir src store amp amp touch src store index tsCopy the following code into the index ts file reference import configureStore from reduxjs toolkit import counterReducer from features counter counterSlice export const store configureStore reducer counter counterReducer export type RootState ReturnType lt typeof store getState gt export type AppDispatch typeof store dispatch First Feature Slice Counter Create a folder called features in the src store folder and create a file called counter counterSlice ts inside it You can run the following command in the terminal to create the folder and file mkdir src store features counter amp amp touch src store features counter counterSlice tsCopy the following code into the counterSlice ts file import createSlice from reduxjs toolkit import type PayloadAction from reduxjs toolkit export interface CounterState value number const initialState CounterState value export const counterSlice createSlice name counter initialState reducers increment state gt state value decrement state gt state value incrementByAmount state action PayloadAction lt number gt gt state value action payload export const increment decrement incrementByAmount counterSlice actions export default counterSlice reducer Creating a Types for the Store StateIn this section we will create a types for the store state Create a file called storeState ts in the src types folder You can run the following command in the terminal to create the file touch src types storeState tsCopy the following code into the storeState ts file INFO serif Counter State Typesexport interface CounterState value number Generate Types with cloudbeds webpack module federation types plugin Optional In this section we will generate types for the store state federation config json file is already configured to like below name container exposes Button src components Button tsx types storeState src types storeState ts Run the following command in the terminal to generate types npx make federated typescontainer d ts looks like below other typesdeclare module container types storeState export interface CounterState value number other typesCongratulations You have successfully generated types for the store state After copy to the container d ts file in remote application Creating Hooks for StoreIn this section we will create a custom hook to access the store and dispatch actions Create a file called useStore ts in the src hooks folder You can run the following command in the terminal to create the file touch src hooks useStore tsCopy the following code into the useStore ts file import useStoreDispatch from useStoreDispatch import decrement increment incrementByAmount from store features counter counterSlice export default function useStore const dispatch useStoreDispatch const incrementCounter gt dispatch increment const decrementCounter gt dispatch decrement const incrementByAmountCounter amount number gt dispatch incrementByAmount amount return incrementCounter decrementCounter incrementByAmountCounter Create a file called useStoreDispatch ts in the src hooks folder You can run the following command in the terminal to create the file touch src hooks useStoreDispatch tsCopy the following code into the useStoreDispatch ts file import useDispatch from react redux import AppDispatch from store export const useStoreDispatch gt AppDispatch useDispatch Create a file called useStoreSelector ts in the src hooks folder You can run the following command in the terminal to create the file touch src hooks useStoreSelector tsCopy the following code into the useStoreSelector ts file import useSelector from react redux import type TypedUseSelectorHook from react redux import RootState from store export const useStoreSelector TypedUseSelectorHook lt RootState gt useSelector Creating a Store ProviderIn this section we will create a store provider component to wrap the application with Create a file called StoreProvider tsx in the src providers folder You can run the following command in the terminal to create the file touch src providers StoreProvider tsxCopy the following code into the StoreProvider tsx file import React PropsWithChildren from react import Provider from react redux import store from store export default function ReduxProvider children PropsWithChildren return lt Provider store store gt children lt Provider gt Wrapping the App with the Store ProviderIn this section we will wrap the application with the store provider Open the src index tsx file and wrap the App component with the StoreProvider component and it should look like the following import React Suspense from react import as ReactDOMClient from react dom client import index css import StoreProvider from providers StoreProvider const TestPage React lazy gt import remote TestPage remote is the name of the containerconst App gt lt div className max w xl mx auto mt text xl text red gt lt div gt Name container lt div gt lt div gt Framework React lt div gt lt div gt Language TypeScript lt div gt lt div gt CSS Tailwind lt div gt lt Suspense fallback lt div gt Loading lt div gt gt lt TestPage gt lt Suspense gt lt div gt const container document getElementById app const root ReactDOMClient createRoot container root render lt StoreProvider gt lt App gt lt StoreProvider gt Export the Store Store Selector and Store Provider in webpackIn this section we will export the store store selector and store provider in webpack Open the webpack config js file and add the following code to the exposes object const HtmlWebPackPlugin require html webpack plugin const ModuleFederationPlugin require webpack lib container ModuleFederationPlugin const configs appName container appFileName remoteEntry js development PUBLIC PATH http localhost REMOTE PATH remote http localhost remoteEntry js PORT production PUBLIC PATH http localhost REMOTE PATH remote http localhost remoteEntry js PORT const deps require package json dependencies module exports env argv gt console log env argv configs configs argv mode return output publicPath configs argv mode PUBLIC PATH resolve extensions tsx ts jsx js json devServer hot true port configs argv mode PORT historyApiFallback true allowedHosts all headers Access Control Allow Origin Access Control Allow Headers Origin X Requested With Content Type Accept module rules test m js type javascript auto resolve fullySpecified false test css s ac ss i use style loader css loader postcss loader test ts tsx js jsx exclude node modules use loader babel loader plugins new ModuleFederationPlugin name configs appName filename configs appFileName remotes remote configs argv mode REMOTE PATH exposes Button src components Button tsx INFO serif We are exposing the store store selector and store provider here hooks useStore src hooks useStore ts hooks useStoreSelector src hooks useStoreSelector ts providers StoreProvider src providers StoreProvider tsx shared deps react singleton true requiredVersion deps react react dom singleton true requiredVersion deps react dom new HtmlWebPackPlugin template src index html Congratulations You have successfully configured Redux in your application Next Step is to use the store in the remote applicationIn this section we will use the store in the remote application Firstly we will define the type of the useStore hook in the container d ts file declare module container hooks useStore function useStore incrementCounter gt void decrementCounter gt void incrementByAmountCounter amount number gt void export default useStore Secondly we will define the type of the useStoreSelector hook in the container d ts file declare module container hooks useStoreSelector import type CounterState ProductState from container types storeState export type RootState counter CounterState product ProductState export interface TypedUseSelectorHook lt TState gt lt TSelected gt selector state TState gt TSelected TSelected lt Selected unknown gt selector state TState gt Selected Selected export const useStoreSelector TypedUseSelectorHook lt RootState gt Lastly we will define the type of the StoreProvider component in the container d ts file declare module container providers StoreProvider import React from react type Props children React ReactNode export default function StoreProvider children Props JSX Element Wrap the App with the Store ProviderIn this section we will wrap the application with the store provider Open the src App tsx file and wrap the App component with the StoreProvider component and it should look like the following import React from react import index css import as ReactDOMClient from react dom client import Button from container Button import StoreProvider from container providers StoreProvider console log Button const App gt lt div className max w xl mx auto mt text xl text blue gt lt div gt Name remote lt div gt lt div gt Framework react lt div gt lt div gt Language TypeScript lt div gt lt div gt CSS Tailwind lt div gt lt Button gt lt div gt const container document getElementById app const root ReactDOMClient createRoot container root render lt StoreProvider gt lt App gt lt StoreProvider gt Use the store in the remote applicationIn this section we will use the store in the remote application Open the src pages test index tsx file and add the following code import Button from container Button import useStore from container hooks useStore import useStoreSelector from container hooks useStoreSelector import React from react export default function TestPage const decrementCounter incrementByAmountCounter incrementCounter getProductList useStore const counter value product products useStoreSelector state gt state return lt div className p space y border gt lt label className text black gt Test Page From Remote Application lt label gt lt p gt counter value value lt p gt lt section className flex flex row gap x gt lt Button label Decrement buttonType error onClick decrementCounter gt lt Button label Increment buttonType primary onClick incrementCounter gt lt Button label Increment by buttonType warning onClick gt incrementByAmountCounter gt lt Button label Decrement by buttonType info onClick gt incrementByAmountCounter gt lt Button label Get All Product buttonType secondary onClick getProductList gt lt section gt lt section className grid grid cols gap gt products map product gt lt div className flex flex col items center justify center text center text black border border gray rounded lg gap y key product id gt lt div gt product brand lt div gt lt img src product images className object contain w h alt product brand gt lt em gt product price lt em gt lt div gt lt section gt lt div gt Congratulations You have successfully configured Redux in your application Create Async Thunk in the Container ApplicationIn this section we will use the createAsyncThunk function in the container application Firstly we will create a service for the product in the src services file and name it product index and add the following code import ProductListResponse from types export const getProductList async Promise lt ProductListResponse gt gt const response await fetch const data await response json return data Add the ProductItem amp ProducState type in the src types storeState file and it should look like the following INFO serif Product State Typesexport interface ProductItem id number title string description string price number discountPercentage number rating number stock number brand string category string thumbnail string images string export interface ProductState products ProductItem other typesCreate type for the product in the src services product types file and name it index and add the following code import ProductItem from types storeState export type ProductListResponse products ProductItem limit number skip number total number We create new slice in the src store features file and name it product and add productSlice ts file in it The productSlice ts file should look like the following import createAsyncThunk createSlice from reduxjs toolkit import type PayloadAction from reduxjs toolkit import ProductItem ProductState from types storeState import getProductList from services product const initialState ProductState products export const getAllProduct createAsyncThunk product getAllProduct async gt try const list await getProductList return list products catch error throw new Error Error while fetching products export const productSlice createSlice name product initialState reducers setProducts state action PayloadAction lt ProductItem gt gt state products action payload extraReducers builder gt builder addCase getAllProduct fulfilled state action gt state products action payload export const setProducts productSlice actions export default productSlice reducer Add the producSlice to src store index ts file should look like the following import configureStore from reduxjs toolkit import counterReducer from features counter counterSlice import productReducer from features product productSlice export const store configureStore reducer counter counterReducer product productReducer export type RootState ReturnType lt typeof store getState gt export type AppDispatch typeof store dispatch Add the getAllProduct to useStore hook in the src container hooks useStore file and it should look like the following import useStoreDispatch from useStoreDispatch import decrement increment incrementByAmount from store features counter counterSlice import getAllProduct from store features product productSlice export default function useStore const dispatch useStoreDispatch const incrementCounter gt dispatch increment const decrementCounter gt dispatch decrement const incrementByAmountCounter amount number gt dispatch incrementByAmount amount const getProductList gt dispatch getAllProduct return incrementCounter decrementCounter incrementByAmountCounter getProductList Congratulations You have successfully added getAllProduct thunk in your application Let s invoke the function on remote application Invoke the getAllProduct thunk in the remote applicationIn this section we will invoke the getAllProduct thunk in the remote application Firstly we will update the useStore hook type on container d ts file and it should look like the following eslint disable lt reference types react gt declare module container Button import React ComponentProps from react import type VariantProps from class variance authority type ButtonElementProps ComponentProps lt button gt export interface ButtonProps extends ButtonElementProps VariantProps lt typeof buttonStyles gt label string icon React ReactNode rightIcon React ReactNode buttonWrapperClassName string const buttonStyles props buttonType error default success primary secondary warning info null undefined size default sm lg xl xxl null undefined padding default sm lg xl xxl null undefined rounded none default full sm lg xl xxl null undefined isFullWidth boolean null undefined amp import class variance authority dist types ClassProp undefined gt string function Button label buttonType rounded padding size isFullWidth className buttonProps ButtonProps React JSX Element export default Button declare module container hooks useStore function useStore incrementCounter gt void decrementCounter gt void incrementByAmountCounter amount number gt void getProductList gt void export default useStore declare module container types storeState export interface ProductItem id number title string description string price number discountPercentage number rating number stock number brand string category string thumbnail string images string export interface ProductState products ProductItem export interface CounterState value number declare module container hooks useStoreSelector import type CounterState ProductState from container types storeState export type RootState counter CounterState product ProductState export interface TypedUseSelectorHook lt TState gt lt TSelected gt selector state TState gt TSelected TSelected lt Selected unknown gt selector state TState gt Selected Selected export const useStoreSelector TypedUseSelectorHook lt RootState gt declare module container providers StoreProvider import React from react type Props children React ReactNode export default function StoreProvider children Props JSX Element Now we will invoke the getProductList function in the remote application src pages test index tsx file and it should look like the following import Button from container Button import useStore from container hooks useStore import useStoreSelector from container hooks useStoreSelector import React from react export default function TestPage const decrementCounter incrementByAmountCounter incrementCounter getProductList useStore const counter value product products useStoreSelector state gt state return lt div className space y gt lt section className grid grid cols gap gt products map product gt lt div className flex flex col items center justify center text center text black border border gray rounded lg gap y key product id gt lt div gt product brand lt div gt lt img src product images className object contain w h alt product brand gt lt em gt product price lt em gt lt div gt lt section gt lt h className text blue md text gray gt Test Page lt h gt value lt Button label Decrement buttonType error onClick decrementCounter gt lt Button label Increment buttonType primary onClick incrementCounter gt lt Button label Increment by buttonType warning onClick gt incrementByAmountCounter gt lt Button label Decrement by buttonType info onClick gt incrementByAmountCounter gt lt Button label Get All Product buttonType secondary onClick getProductList gt lt div gt Run the Container amp Remote ApplicationIn this section we will run the application Open the terminal and run the following command cd container amp amp npm run startcd remote amp amp npm run startCongratulations You have successfully configured Redux in your application ConclusionRedux and Redux Toolkit Installation You started by installing Redux and Redux Toolkit using the provided npm command Redux Store Configuration You created a centralized Redux store configuration setting up the initial state and reducers for the counter feature Feature Slice Creation You created a feature slice for the counter which encapsulates the state and reducers specific to the counter feature Types for Store State You defined types for the store state in a separate file to ensure type safety throughout your application Custom Hooks for Store You created custom hooks for accessing the store and dispatching actions abstracting away the complexity of directly interacting with Redux Store Provider Component You created a store provider component to wrap your application and provide access to the Redux store to all components within the app Webpack Configuration You configured Webpack to expose the necessary hooks components and types allowing your remote application to access the Redux related functionality from the container Async Thunk for Remote Application You expanded the functionality by adding an asynchronous thunk for fetching product data demonstrating how to fetch data from a remote source and update the store Using the Store in the Remote Application You showcased how to use the custom hooks and selectors in the remote application incorporating Redux state management seamlessly into your micro front end architecture Running the Applications Finally you learned how to run both the container and remote applications concurrently to see your Redux powered micro front end in action By following this guide you ve gained a solid understanding of how to effectively integrate Redux and Redux Toolkit into a micro front end architecture enhancing the maintainability scalability and user experience of your applications This approach allows you to create independent and reusable components while managing the state centrally leading to more organized and efficient development processes Thank you for reading this article If you have any questions or suggestions please feel free to reach out to me on Twitter | 2023-08-19 12:41:06 |
海外TECH | CodeProject Latest Articles | JSON Web Token Authentication in RESTful API .NET Core 7.0 | https://www.codeproject.com/Articles/5366863/JSON-Web-Token-Authentication-in-RESTful-API-NET-C | authentication | 2023-08-19 12:45:00 |
ニュース | BBC News - Home | Lucy Letby: Concerns inquiry will not have enough powers | https://www.bbc.co.uk/news/uk-66553245?at_medium=RSS&at_campaign=KARANGA | letby | 2023-08-19 12:17:01 |
ニュース | BBC News - Home | Women's World Cup final: How England became good at women’s football | https://www.bbc.co.uk/sport/football/66533140?at_medium=RSS&at_campaign=KARANGA | world | 2023-08-19 12:45:42 |
コメント
コメントを投稿