python |
Pythonタグが付けられた新着投稿 - Qiita |
idとctypes |
https://qiita.com/thmd9726/items/6c434ba8127e323c4e19
|
ctypespython |
2021-05-31 00:58:28 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
int()の例外がTypeErrorになるケース、ValueErrorになるケース |
https://qiita.com/boma/items/7c8e90bd1468d747eb31
|
intの例外がTypeErrorになるケース、ValueErrorになるケースintでstring型をint型に変換したときの例外が、TypeErrorになるケース、ValueErrorになるケースを忘れてしまうので、メモとして残します。 |
2021-05-31 00:34:33 |
python |
Pythonタグが付けられた新着投稿 - Qiita |
GitHub Actionsを使ってSOTA論文通知用Slack botを作る |
https://qiita.com/ryamad/items/03fb48d5d0328f83a0d2
|
そこで、SOTAが更新されると、SOTAモデルとその提案論文をSlackに通知するbotを作りました。 |
2021-05-31 00:08:20 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
JavaScript 正弦波入力の入れ方 |
https://teratail.com/questions/341268?rss=all
|
javascript |
2021-05-31 00:48:13 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
android ダークテーマ切り替え 再起動なしで行う方法 |
https://teratail.com/questions/341267?rss=all
|
androidダークテーマ切り替え再起動なしで行う方法実現したいことアプリ内で、ライトテーマとダークテーマを手動で切り替える機能を実装したいのですが、切り替え時にアクティビティを再起動せずにテーマを切り替える方法はありますか具体的なイメージは、以下の画像のようにアクティビティの再起動なしで、テーマや色のみを変える処理を実現したいです。 |
2021-05-31 00:41:47 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
【Rails API】CarrierWaveでの画像投稿が出来なかった際の、レスポンスをJson形式で渡す方法 |
https://teratail.com/questions/341266?rss=all
|
【RailsAPI】CarrierWaveでの画像投稿が出来なかった際の、レスポンスをJson形式で渡す方法現在画像ファイルを投稿する際、下記コードのnbspextensionwhitelistmnbspメソッドにより保存できるファイルを制限しています。 |
2021-05-31 00:21:59 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
mecabのユーザー辞書を作成したがpythonから利用するとエラーが起こる |
https://teratail.com/questions/341265?rss=all
|
mecabのユーザー辞書を作成したがpythonから利用するとエラーが起こるMnbspmacを利用してます。 |
2021-05-31 00:18:52 |
Program |
[全てのタグ]の新着質問一覧|teratail(テラテイル) |
Python+requestsにて302エラーが発生 |
https://teratail.com/questions/341264?rss=all
|
Pythonrequestsにてエラーが発生前提・実現したいことpythonrequestsにてpostを実行し目的の画面に遷移させたい。 |
2021-05-31 00:15:50 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
【React】useStateでstateで画面の表示切替する |
https://qiita.com/GalaxyNeko/items/b54d287805798dc31124
|
reactuseEffectで最初に読み込まれた時のあたいを設定していますuseEffectgtsetValueLOADINGsetvalueHandlerではイベントごとに値を設定しなおしていますsetValueHandlersetValueSUCEESSreturn以下は値に合わせて条件式画面に表示させる値を変更していますINITIAL状態の画面→LOADING状態の画面SUCCESS状態の画面が表示されるようになります。 |
2021-05-31 00:19:10 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
eachの入れ子 問題 |
https://qiita.com/tatsunori-abe/items/a7a256f32ccc55e17151
|
この配列を用いて、果物の名前とそれぞれの合計額が出力されるコードを記述してください。 |
2021-05-31 00:15:14 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
mini_magickで縦書き文字入り画像を生成 |
https://qiita.com/kawaidbz/items/628a1164d23b81407ca6
|
minimagickで縦書き文字入り画像を生成概要rubyで画像処理を行うことができるgemである「minimagick」を使用し、縦書き文字入りの画像を生成する方法です。 |
2021-05-31 00:14:24 |
Ruby |
Rubyタグが付けられた新着投稿 - Qiita |
DiscordのBotを作ってみよう!②メッセージとコマンドに反応するBot |
https://qiita.com/tomynomint/items/90328c431316772a4e89
|
実行してみましょう名前さん、サーバ名へようこそと返ってきましたこのように変数usernameや変数servernameなどを使えば、送信したユーザに応じて名前を変えるコマンドの実行に成功しましたメッセージから値を色々とってみよう他にもいろんな値が取得することができます。 |
2021-05-31 00:09:05 |
Linux |
Ubuntuタグが付けられた新着投稿 - Qiita |
Ubuntu 20.04 で OpenZFS 最新版を導入する |
https://qiita.com/yamakenjp/items/380ea5bb338940b5dc55
|
UbuntuでOpenZFS最新版を導入するUbuntu環境で、最新のOpenZFSを使う方法です。 |
2021-05-31 00:03:18 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
(作業中)『OSS-DB標準教科書』2_SQLによるDBの操作 基礎 |
https://qiita.com/ume-san/items/59ffb9eaf8c5903f9b55
|
GUIに反映されていない・・・・テーブルで右クリックし、更新をクリックしてみると、orders表だけが反映されましたprod表とcustomer表は、どこへ行ってしまったのでしょうかもしや、私はCREATE文つを一度に記述して、一度に実行しようとしたけれど、それで実行できたのは最終行のorders表だけで、行目と行目は、実は個別に実行しなくてはならなかったのでしょうか試してみます。 |
2021-05-31 00:21:41 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Dockerfileを作成してbuildする際にハマったこと |
https://qiita.com/gbf_abe/items/2bf45206c515cea75d9b
|
Dockerfileを作成してbuildする際にハマったこと概要Dockerを基本から学ぶ上記書籍を参考にDockerfileを作る→ビルドするという流れで遊んでいたら思いの外ハマったのでそのときの解決方法とかを共有します実行環境・PCMacBookProinchFourThunderboltportsMじゃないやつです・DockerVersion遭遇したエラー①hogehogedockerbuildttestapacheBuildingsgtERRORinternalloadbuilddefinitionfromDockerfilesgtgttransferringdockerfileBsgtinternalloadbuilddefinitionfromDockerfilefailedtosolvewithfrontenddockerfilevfailedtoreaddockerfileerrorfromsenderopenTrashoperationnotpermitted原因ホームディレクトリにDockerfileが存在している解決方法参考書籍ではmkdirdocumentでディレクトリを作成しているので、documentにファイルを移動した遭遇したエラー②hogehogedocumentdockerbuildttestapacheBuildingsFINISHEDgtinternalloadbuilddefinitionfromDockerfilesgtgttransferringdockerfileBsgtinternalloaddockerignoresgtgttransferringcontextBsgtinternalloadmetadatafordockeriolibrarycentoslatestsgtauthlibrarycentospulltokenforregistrydockeriosgtinternalloadbuildcontextsgtgttransferringcontextBsgtCANCELEDFROMdockeriolibrarycentosshaebbdcedcdcabedfebcdeacbcefcsgtgtresolvedockeriolibrarycentosshaebbdcedcdcabedfebcdeacbcefcsgtgtshaebbdcedcdcabedfebcdeacbcefcBBsgtgtshadbbaceccbcffaecabacbbbfBBsgtgtshaeadbfafefbbfaefebddebbafkBkBsgtCACHEDRUNyumyupdatesgtCACHEDRUNyumyinstallhttpdsgtERRORADDdocumentindexhtmlvarwwwhtmlindexhtmlsgtADDdocumentindexhtmlvarwwwhtmlindexhtmlfailedtocomputecachekeyfailedtowalkvarlibdockertmpbuildkitmountdocumentlstatvarlibdockertmpbuildkitmountdocumentnosuchfileordirectoryDockerfileの内容を調べてみるhogehogedocumentcatDockerfileFROMcentosRUNyumyupdateRUNyumyinstallhttpdADDdocumentindexhtmlvarwwwhtmlindexhtmlEXPOSECMDusrsbinhttpdDFOREGROUNDどうやらこの記事に書いてあることが怪しい【docker】ビルドコンテキストbuildcontextとは内容を私が理解した形で書くと、dockerbuild時にコピーするファイルビルドコンテキストを指定するときは相対パスカレントディレクトリからのパスで指定する必要があるらしいDockerfileの行目はADDdocumentindexhtmlvarwwwhtmlindexhtmlとしているので、これは間違っているということになるDockerfileの内容を修正してみるhogehogedocumentvimDockerfilehogehogedocumentcatDockerfileFROMcentosRUNyumyupdateRUNyumyinstallhttpdADDindexhtmlvarwwwhtmlindexhtmlEXPOSECMDusrsbinhttpdDFOREGROUNDhogehogedocumentdockerbuildttestapacheBuildingsFINISHEDgtinternalloadbuilddefinitionfromDockerfilesgtgttransferringdockerfileBsgtinternalloaddockerignoresgtgttransferringcontextBsgtinternalloadmetadatafordockeriolibrarycentoslatestsgtauthlibrarycentospulltokenforregistrydockeriosgtFROMdockeriolibrarycentosshaebbdcedcdcabedfebcdeacbcefcsgtgtresolvedockeriolibrarycentosshaebbdcedcdcabedfebcdeacbcefcsgtgtshaebbdcedcdcabedfebcdeacbcefcBBsgtgtshadbbaceccbcffaecabacbbbfBBsgtgtshaeadbfafefbbfaefebddebbafkBkBsgtgtshaafffbedadcaefcebbbacecMBMBsgtgtextractingshaafffbedadcaefcebbbacecsgtinternalloadbuildcontextsgtgttransferringcontextBsgtRUNyumyupdatesgtRUNyumyinstallhttpdsgtADDindexhtmlvarwwwhtmlindexhtmlsgtexportingtoimagesgtgtexportinglayerssgtgtwritingimageshaebbfcaabbffeccccbbcddcsgtgtnamingtodockeriotestapachesUsedockerscantorunSnyktestsagainstimagestofindvulnerabilitiesandlearnhowtofixthemビルドできたっぽいdockerimagesを実行してみるhogehogedocumentdockerimagesREPOSITORYTAGIMAGEIDCREATEDSIZEtestapachelatestebbfcAboutaminuteagoMBおお、できてるおわりに人によっては結構ハマる気がするので、この問題でハマったの参考になれば嬉しいです。 |
2021-05-31 00:09:41 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
rails sエラーの原因がsqliteのバージョン |
https://qiita.com/program9989/items/b04467ca6fc521a0f9dd
|
railssエラーの原因がsqliteのバージョンPumacaughtthiserrorErrorloadingthesqliteActiveRecordadapterMissingagemitdependsoncantactivatesqlitegtalreadyactivatedsqliteMakesurealldependenciesareaddedtoGemfileLoadErrorバージョン系しか使えないのに、を使おうとしている。 |
2021-05-31 00:40:21 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
rails sが実行できない。webpackerエラーで、yarnがないのが原因 |
https://qiita.com/program9989/items/d54e7559b418a02dfcb9
|
railss |
2021-05-31 00:29:35 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
【React】useStateでstateで画面の表示切替する |
https://qiita.com/GalaxyNeko/items/b54d287805798dc31124
|
reactuseEffectで最初に読み込まれた時のあたいを設定していますuseEffectgtsetValueLOADINGsetvalueHandlerではイベントごとに値を設定しなおしていますsetValueHandlersetValueSUCEESSreturn以下は値に合わせて条件式画面に表示させる値を変更していますINITIAL状態の画面→LOADING状態の画面SUCCESS状態の画面が表示されるようになります。 |
2021-05-31 00:19:10 |
Ruby |
Railsタグが付けられた新着投稿 - Qiita |
mini_magickで縦書き文字入り画像を生成 |
https://qiita.com/kawaidbz/items/628a1164d23b81407ca6
|
minimagickで縦書き文字入り画像を生成概要rubyで画像処理を行うことができるgemである「minimagick」を使用し、縦書き文字入りの画像を生成する方法です。 |
2021-05-31 00:14:24 |
海外TECH |
Ars Technica |
Movie written by algorithm turns out to be hilarious and intense |
https://arstechnica.com/?p=896589
|
sunspring |
2021-05-30 15:55:36 |
海外TECH |
DEV Community |
MobX State Tree (MST) - State Management |
https://dev.to/kpiteng/mobx-state-tree-mst-state-management-5h6o
|
MobX State Tree MST State ManagementHello Developers Everyone uses various State Management library on their Application many of us already use Redux Redux Saga Redux Rematch Today we will explore MobX which is the most popular Redux alternative MobX State Tree MST is the powerful state management library which you can use from small to enterprise grade applications and it s very simple to plug amp play I will take you from core concept to component level integration So let s continue What will we cover What is MobX State Tree Why should I use MobX State Tree MobX State Tree InstallationGetting Started MobX EntityCreating ModelCreating Model InstanceMeeting TypesModifying DataSnapshotSnapshot to ModelGetting to the UIImproving Render PerformanceComputed PropertiesReferences What is MobX State Tree MobX State Tree MST is a reactive state management library It is a container system built on MobX MobX State Management Engine and MobX State Tree gives you a structure which has type state to store your data MST is most preferable from Small to Enterprise grade application where code amp functionality is going to scale periodically Compare to Redux MST offer powerful performance and less lines of code MobX supports an array of features for a modern state management system and everything in one package MobX not more extra dependency Why should I use MobX State Tree MST have many props compare to other state management Lets check few of them MST offers great compatibility with React Native ReactJS VueJS AngularJS and more JavaScript apps Instead of messy code everywhere in the app MST gives centralized stores to quick access and exchange data Encapsulation Your data can t be modified by outside It can be modified in “actions So it s easy to access but secure from outside access Runtime type checking help you to write clean code and prevent users from assigning wrong data to a tree Whatever you change in the State is tracked and you can create a snapshot of your state at any time MobX State Tree InstallationAs we discussed earlier MobX is State Management and MobeX State Tree give you structure to store your data So we need to install mobx mobx state tree NPM npm install mobx mobx state tree saveYarn yarn add mobx mobx state treeLet s create react app npx create react app todo appNow let s install dependency npm install mobx mobx state tree mobx react liteRun ToDo App npm run start Getting Started MobX EntityLet s start by creating a ToDo application ToDo application have two entities Task and User Task entity have two attributes taskName name of task taskStatus to identify tasks completed or not User entity have two attributes userID id of User userName name of User So our entities will looks like something TasktaskNametaskStatusUseruserIDuserName Creating ModelTree Type State Each tree has a shape type information and state data Create model with types modelimport types from mobx state tree const Task types model taskName taskStatus false const User types model userID userName Creating Model InstanceSimply create instance by calling create import types getSnapshot from mobx state tree const Task types model taskName taskStatus false const User types model userID userName const kpiteng User create const articleWriting Task create taskName “Article Writing console log User kpiteng getSnapshot kpiteng console log Task articleWriting getSnapshot articleWriting Meeting TypesMobX checks runtime type checking helps developers to identify wrong data passed in argument This is very helpful while multiple developers are involved in large scale application const articleWriting Task create taskName Article Writing taskStatus Here You will get an error like is not assignable to type boolean as you have take taskStatus as boolean so you can t pass integer data type const Task types model taskName types optional types string taskStatus types optional types boolean false const User types model userID types optional types number userName types optional types string The types namespace are derived from the MST package You can check lots of widely usage types like array map maybe union and many more You can check various types available in MST Now It s time to create a root model let s combine Task and User model import types from mobx state tree const Task types model taskName types optional types string taskStatus types optional types boolean false const User types model userID types optional types number userName types optional types string const RootStore types model users types map User tasks types optional types map Task const store RootStore create users Note If you are not passing default model value on create then you must specify default value of in second argument of types optional arg arg Modifying DataMST Tree node only modified in actions only const Task types model taskName types optional types string taskStatus types optional types boolean false actions self gt setTaskName newTaskName self taskName newTaskName toggle self taskStatus self taskStatus const User types model userID types optional types number userName types optional types string const RootStore types model users types map User tasks types map Task actions self gt addTask userID taskName self tasks set userID Task create taskName const store RootStore create users store addTask Article Writing store tasks get toggle render lt div gt JSON stringify getSnapshot store lt div gt document getElementById root users taks taskName Article Writing taskStatus true Have you noticed self self object constructed when an instance of your model is created It s this free you can access it using self SnapshotLet s say you want to see the value stored in your state which means take a look at a snapshot It s simple using getSnapshot Every Time when you update your state and want to check if changes are reflected in the state you can check using getSnapshot To listen to state change you an use this onSnapshot store snapshot gt console log snapshot console log getSnapshot store users tasks taskName Article Writing taskCompleted true Snapshot to ModelIn the previous step we see we retrieved a snapshot from the model But Is that possible to restore the model from the snapshot Yes it s simple Let s see how Before that I would like to relate this process with Redux so you quickly understood In Redux we have Reducer where we have State and we initialize State variables with default values like users tasks Now first time when user open application we haven t any snapshot empty store so store will refill using model s default value default state value After interaction with the application you have updated values in store When you come back next time it will fetch data from the store and refill your model state This same process we are going to do here In MobeX we can achieve this using two different ways First by passing default store value Second passing store and default store value snapshot value stconst store RootStore create users tasks taskName Article Writing taskStatus true ndapplySnapshot store users tasks taskName Article Writing taskStatus true Getting to the UINow it s time to work with the UI to connect the MST store to React Component we required mobex react lite We are going to use an observer name it self say everything It s simple it observe store and updates React components Render React components whenever anything changed in the store import observer from mobx react lite import values from mobx const App observer props gt lt div gt lt button onClick e gt props store addTask randomId Article Writing gt Add Task lt button gt values props store tasks map todo gt lt div gt lt input type checkbox checked task taskStatus onChange e gt task toggle gt lt input type text value task taskName onChange e gt task setTaskName e target value gt lt div gt lt div gt Improving Render PerformanceIn Previous steps we have rendered Tasks for each task we have given the option to mark it complete Now everytime we check uncheck the task our UI will render because we have added an observer It s observer duty to update components when anything updates on the store So how to avoid this re rendering situation It s simple let s see it const TaskView observer props gt lt div gt lt input type checkbox checked props task taskStatus onChange e gt props task toggle gt lt input type text value props task taskName onChange e gt props task setTaskName e target value gt lt div gt const AppView observer props gt lt div gt lt button onClick e gt props store addTask randomId Article Writing gt Add Task lt button gt values props store tasks map task gt lt TaskView task task gt lt div gt We have separate business logic for TaskView Note we have added an observer in TaskView So when anyone changes TaskStatus Check UnCheck only TaskView will be rendered AppView only re render in a case when a new task is added or existing task deleted Computed PropertiesTill previous steps we are showing Tasks added by User What I need to do to show the count of Completed Tasks and Pending Tasks It s simple with MobX add getter property in our model by calling views it will count how many Tasks completed and pending Let s see the code const RootStore types model users types map User tasks types map Task views self gt get pendingTasksCount return values self tasks filter task gt task taskStatus length get completedCount return values self tasks filter task gt task done length actions self gt addTask userID taskName self tasks set userID Task create taskName const TaskCountView observer props gt lt div gt props store pendingTaskCount Pending Tasks props store completedTaskCount Completed Tasks lt div gt const AppView observer props gt lt div gt lt button onClick e gt props store addTask randomId Article Writing gt Add Task lt button gt values props store tasks map task gt lt TaskView task task gt lt TaskCountView store props store gt lt div gt Do you want to start new project check React Ignite Boilerplate ReferencesNow it s time to assign a User for each Task in Tasks For this we need to tell MST which is the unique attribute primary key in db language in each User model instance You can implement it using types identifier type composer const User types model userID types identifier userName types optional types string Now we need to define a reference to the Task Model It s simple you can do it using types reference User Many times it s a circular reference so to resolve it we need to use types late gt User It may be possible User entry found null to resolve that we need to use type maybe So finally let s see how code looks like const Task types model taskName types optional types string taskStatus types optional types boolean false user types maybe types reference types late gt User actions self gt setTaskName newTaskName self taskName newTaskName setUser user if user self user undefined else self user user toggle self taskStatus self taskStatus const UserPickerView observer props gt lt select value props user props user userID onChange e gt props onChange e target value gt lt option value gt none lt option gt values props store users map user gt lt option value user id gt user name lt option gt lt select gt const TaskView observer props gt lt div gt lt input type checkbox checked props task taskStatus onChange e gt props task toggle gt lt input type text value props task name onChange e gt props task setName e target value gt lt UserPickerView user props task user store props store onChange userID gt props task setUser userID gt lt div gt const TaskCountView observer props gt lt div gt props store pendingTaskCount Pending Tasks props store completedTaskCount Completed Tasks lt div gt const AppView observer props gt lt div gt lt button onClick e gt props store addTask randomId Article Writting gt Add Task lt button gt values props store tasks map task gt lt TaskView store props store task task gt lt TaskCountView store props store gt lt div gt We have covered almost all required topics from MobeX State Tree MobeX provided few sample example download ToDoMVC app using React and MST and Bookshop app with references identifiers routing testing etc Thanks for reading Article KPITENG DIGITAL TRANSFORMATIONwww kpiteng com blogs hello kpiteng comConnect Follow Us On Linkedin Facebook Instagram |
2021-05-30 15:02:13 |
海外TECH |
DEV Community |
Using JS Intersection Observer API to track user footprints |
https://dev.to/harshit369/using-js-intersection-observer-api-to-track-user-footprints-23c2
|
Using JS Intersection Observer API to track user footprintsUnderstanding user behavior for your web app to find out where the disconnect is and which of your features is giving a hard time to your users is no more a secondary thing If you try googling for some good ready to integrate solutions to track users you will find some big and established players like Google Analytics and Mixpanel who also serve you with exceptional metrics and dashboards based on the data you publish to them Now your respective teams can analyze this data and zoom into the actual pain points and gaps But what if you had a use case like we did where a user had to pay for each visit depending on the time they spent and the features they strolled over during their time on the platform The question that comes out is this data first of all exposed and secondly reliable enough to cut someone a ticket The answer was NO All because integrating most of these libraries effectively requires a lot of SDK calls to be integrated across your whole app like landmines So without boring you any further with the back story of why let s jump to After weighing the effectiveness and integration efforts we decided to rely on the browser s IntersectionObserver API to rescue us It lets you observe elements in your DOM tree and dispatches an event when one of those elements enters or exits the viewport Let s put some code where my mouth is Tracking ServiceFirst we needed a service that can work as a singleton to observe and track different components in your viewport and also independently integrate with the backend service function createObserver options you can understand the meaning of each options values here creating an intersection observer let options root document querySelector window rootMargin px options let observer new IntersectionObserver entries gt entries forEach entry gt do something when some target changes state enters or exits viewport options return observe function id details element observer observe element unobserve function id details element observer unobserve element export default createObserver So what s happening here is we created function createObserver an abstraction that exposes two fundamental methods observe this will help us register our components nodes to the observer So that it can start tracking and notify us once the state of the element changes unobserve Just opposite to the observe method its job is to de register the element from the observer and stop if there s any already running timer Now these two simple methods work for most of the cases but there s one particular case when the whole app un mounts and we still had few running timers In that case we need to maintain an in memory map of all elements being tracked and expose another method unobserveAll that would just unobserve all records before going down function createObserver options const observingTargets let options let observer new IntersectionObserver entries gt entries forEach entry gt const id entry target getAttribute data observer id if observingTargets id isIntersecting entry isIntersecting observingTargets id isIntersecting entry isIntersecting toggle feature timer here API options return observe function id details element observingTargets id id details element observer observe element unobserve function id details element observer unobserve element stop timer API delete observingTargets id unobserveAll function Object keys observingTargets forEach id gt this unobserve observingTargets id export default createObserver With the new code additions we now have a map called observingTargets that holds all the elements under observation and their current state When any of those elements change state for each of them we update the record and a boolean isIntersecting property telling the current state The only thing remaining now is to hit the backend service API to start stop the timer Let s add that as well and then we can rub our hands and integrate it with our react components function toggleTimer payload tell api about the state change return axios post timer payload isIntersecting start stop payload details function createObserver options const observingTargets let options let observer new IntersectionObserver entries gt entries forEach entry gt const id entry target getAttribute data observer id if observingTargets id isIntersecting entry isIntersecting observingTargets id isIntersecting entry isIntersecting toggleTimer observingTargets id options return observe function id details element observingTargets id id details element observer observe element unobserve function id details element observer unobserve element overriding isIntersecting to handle the scenario in case app unmounts while element was still in the view port toggleTimer observingTargets id isIntersecting false delete observingTargets id unobserveAll function Object keys observingTargets forEach id gt this unobserve observingTargets id export default createObserver React HOCOn the UI component side of things one has to handle three things Register itself to the observer service using observe and tell it to keep an eye on the component s intersection with the viewport Use unobserve function to de register itself before un mountingCall unobserveAll function that will stop all the running timers once a user decides to leave your app The third one can be handled using the window s beforeunload event which is called right before the tab unloads So for our React components we ll be focussing on the first two HOC stands for Higher Order Component It s not something specific to React and lets you extend your components compositionally As per official React documentation Concretely a higher order component is a function that takes a component and returns a new component So let s implement it import React from react import ReactDOM from react dom import observer from observer const TrackedEl function ElToTrack id details return class extends React Component node null providing the ability to override the id attribute before mounting this will be useful when you have multiple children of same type either through a map of something id this props data observer id id render return lt ElToTrack this props gt componentDidMount this node ReactDOM findDOMNode this observer observe element this node id this id details id this id details componentWillUnmount observer unobserve element this node id this id details id this id details export default TrackedEl What we implemented above is a function that returns our custom component which renders the very same component in the render method that needs to be tracked and was passed to it as the first param Additionally it takes care of both registering observe and unregistering unobserve the actual DOM node using component lifecycle hooks PS This can also re written using a lot of React Hooks shorthands you can try but I find it easier to convey the message with the legacy API Now let s see how it can be used with our components const NormalReactComponent props gt return lt div id id gt Hey i m being tracked lt div gt export default TrackedEL NormalReactComponent id That s it Now all we need to track our components is to wrap them with the TrackedEL HOC that will take care of all observing and un observing logic using the functions exposed by the timer service created above So now at the end of it we have a well crafted easy to integrate and extensible way to track our components and in premise user data that can be relied upon as well as easily reconciled You can find the whole working code in this sandbox Suggestions and corrections would be really appreciated Happy Tracking |
2021-05-30 15:01:26 |
海外TECH |
Engadget |
Tesla may have to ship Texas-made EVs out of state to sell them to Texans |
https://www.engadget.com/tesla-affected-by-texas-dealership-laws-152618312.html?src=rss_b2c
|
Tesla may have to ship Texas made EVs out of state to sell them to TexansTesla may have to ship EVs made in Texas out of the state to sell them to local customers due to pro dealership laws that haven t been changed |
2021-05-30 15:26:18 |
金融 |
◇◇ 保険デイリーニュース ◇◇(損保担当者必携!) |
保険デイリーニュース(05/31) |
http://www.yanaharu.com/ins/?p=4587
|
損保ジャパン |
2021-05-30 15:00:41 |
ニュース |
BBC News - Home |
French Open 2021: Naomi Osaka faces default from Grand Slam for refusing to speak to media |
https://www.bbc.co.uk/sport/tennis/57301475
|
French Open Naomi Osaka faces default from Grand Slam for refusing to speak to mediaWorld number two Naomi Osaka faces expulsion from the French Open if she continues to refuse to speak to the media |
2021-05-30 15:46:20 |
ニュース |
BBC News - Home |
Poots: European Union treating NI as a political plaything |
https://www.bbc.co.uk/news/uk-northern-ireland-57299360
|
peace |
2021-05-30 15:56:28 |
ニュース |
BBC News - Home |
Brexit lorry park 'ruins night sky' for Kent residents |
https://www.bbc.co.uk/news/uk-england-kent-57299121
|
light |
2021-05-30 15:11:08 |
ニュース |
BBC News - Home |
Moto3 rider Dupasquier dies after crash in qualifying |
https://www.bbc.co.uk/sport/motorsport/57299713
|
italy |
2021-05-30 15:22:17 |
サブカルネタ |
ラーブロ |
21/153 用心棒 本号:味玉ラーメン(麺2/3、200g。ニンニクましまし、アブラ、辛たま)、追加豚1枚 |
http://feedproxy.google.com/~r/rablo/~3/WEpZTqQMOTg/single_feed.php
|
配信 |
2021-05-30 16:10:09 |
北海道 |
北海道新聞 |
岩の斜面、純白に染めて テシオコザクラ満開 幌延の北大研究林で |
https://www.hokkaido-np.co.jp/article/549718/
|
宗谷管内 |
2021-05-31 00:16:04 |
北海道 |
北海道新聞 |
全国の介護施設で感染9490人 486人死亡、共同通信調査 |
https://www.hokkaido-np.co.jp/article/549742/
|
介護施設 |
2021-05-31 00:02:03 |
ニュース |
THE BRIDGE |
香港VCのBrinc、欧州Blue Horizonとフードテックアクセラレータを設立——300万米ドル超を投資 |
http://feedproxy.google.com/~r/SdJapan/~3/6BiPdxSyhpM/brinc-launch-3m-foodtech-accelerator-europes-blue-horizon
|
香港VCのBrinc、欧州BlueHorizonとフードテックアクセラレータを設立ー万米ドル超を投資TechinAsiaでは、有料購読サービスを提供。 |
2021-05-30 15:05:12 |
コメント
コメントを投稿