IT |
気になる、記になる… |
米Amazon、ロボット掃除機「ルンバ」シリーズで有名なiRobot社を買収へ |
https://taisy0.com/2022/08/05/159853.html
|
amazon |
2022-08-05 13:15:39 |
IT |
ITmedia 総合記事一覧 |
[ITmedia News] 米Amazon、「ルンバ」のiRobotを買収 |
https://www.itmedia.co.jp/news/articles/2208/05/news192.html
|
amazon |
2022-08-05 22:48:00 |
AWS |
AWS Architecture Blog |
Web application access control patterns using AWS services |
https://aws.amazon.com/blogs/architecture/web-application-access-control-patterns-using-aws-services/
|
Web application access control patterns using AWS servicesThe web application client server pattern is widely adopted The access control allows only authorized clients to access the backend server resources by authenticating the client and providing granular level access based on who the client is This post focuses on three solution architecture patterns that prevent unauthorized clients from gaining access to web application backend servers … |
2022-08-05 13:48:10 |
Docker |
dockerタグが付けられた新着投稿 - Qiita |
Docker 基本のコマンド |
https://qiita.com/kandalog/items/0c2e7076c42e443c06bf
|
dockerfile |
2022-08-05 22:40:38 |
海外TECH |
DEV Community |
What's the difference between Front-end and Back-end development? |
https://dev.to/sloan/whats-the-difference-between-front-end-and-back-end-development-3ed9
|
What x s the difference between Front end and Back end development This is an anonymous post sent in by a member who does not want their name disclosed Please be thoughtful with your responses as these are usually tough posts to write Email sloan dev to if you d like to leave an anonymous comment or if you want to ask your own anonymous question I m brand new to development and am trying to understand the difference between front end and back end development I think I kinda understand that front end is what the user sees and back end is how the information is retrieved but I imagine there s a bit more to it than that I would really appreciate hearing others thoughts and explanations on this Analogies and examples would be very welcomed Thank you all very much |
2022-08-05 13:41:07 |
海外TECH |
DEV Community |
Creating an infinite scroll with React JS! ♾️ |
https://dev.to/franklin030601/creating-an-infinite-scroll-with-react-js-4in5
|
Creating an infinite scroll with React JS ️This time we are going to implement an infinite scroll using React JS An application that implements infinite scroll consists of a layout that allows users to keep consuming a certain amount of information without any pause as the content is automatically loaded as the user scrolls Note This post requires you to know the basics of React with TypeScript basic hooks Any kind of feedback is welcome thank you and I hope you enjoy the article Table of contents Technologies to be used Creating the project First steps Making the API request Showing the cards Making the infinite scroll Refactoring Conclusion Live demo Source code Technologies to be used ️React JS version ️Vite JS ️TypeScript ️React Query ️Rick and Morty API ️CSS vanilla You can find the styles in the repository at the end of this post Creating the project We will name the project infinite scroll optional you can name it whatever you like npm init vite latestWe create the project with Vite JS and select React with TypeScript Then we run the following command to navigate to the directory just created cd infinite scrollThen we install the dependencies npm installThen we open the project in a code editor in my case VS code code First steps First in the src App tsx file we will delete the content and add a title const App gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppNext we are going to create two components that we are going to use later We create the folder src components and inside we create the following files Loading tsxThis file will contain the following export const Loading gt return lt div className container loading gt lt div className spinner gt lt div gt lt span gt Loading more characters lt span gt lt div gt It will be used to show a spinner when a new request is made to the API Card tsxThis file will contain the following import Result from interface interface Props character Result export const Card character Props gt return lt div className card gt lt img src character image alt character name width loading lazy gt lt p gt character name lt p gt lt div gt This is the card that will show the Rick and Morty API character In the src interfaces folder we create an index ts file and add the following interfaces export interface ResponseAPI info Info results Result export interface Info count number pages number next string prev string export interface Result id number name string image string Note The Result interface actually has more properties but in this case I will only use the ones I have defined Making the API request In this case we will use the React Query library that will allow us to perform the requests in a better way and also has other features such as cache management Install the dependencynpm i tanstack react queryAnd then in the src main tsx file we are going to do the following We are going to enclose our App component inside the QueryClientProvider and send it the client which is just a new instance of QueryClient import QueryClient QueryClientProvider from tanstack react query import React from react import ReactDOM from react dom client import App from App import index css const queryClient new QueryClient ReactDOM createRoot document getElementById root as HTMLElement render lt React StrictMode gt lt QueryClientProvider client queryClient gt lt App gt lt QueryClientProvider gt lt React StrictMode gt Now in the src App tsx file we are going to use a special React Query hook called useInfiniteQuery const App gt useInfiniteQuery return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThe useInfiniteQuery hook needs several parameters queryKey an array of strings or nested objects which is used as a key to manage cache storage queryFn a function that returns a promise the promise must be resolved or throw an error options within the options we need one called getNextPageParam which is a function that returns the information for the next query to the API The first parameter is the queryKey in this case we place an array with the word characters const App gt useInfiniteQuery characters return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThe second parameter is the queryFn in this case we place an array with the word characters First we pass it a functionconst App gt useInfiniteQuery characters gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThis function must return a resolved promise For this outside the component we create a function that will receive as parameter the page to fetch and will return a promise of type ResponseAPI import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters gt fetcher return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThe queryFn receives several parameters among them the pageParam that by default will be undefined and then number so if a value does not exist we will equal it to and this property we pass it to the function fetcher import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppNow the last parameter is the options which is an object which we will use the getNextPageParam property import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThe function getNextPageParam receives two parameters but we will only use the first one that is the last page received that is to say the last answer that the API gave us Inside the function as the API of Rick and Morty does not come with the next page rather it comes with the url for the next page we will have to do the following We will obtain the previous page The API response comes the info property that contains the prev property we evaluate if it exists because in the first call the prev property is null If it does not exist then it is page If it exists then we get that string we separate it and get the number const previousPage lastPage info prev lastPage info prev split We will get the current page We just add the previous page plus const currentPage previousPage We will evaluate if there are more pages We evaluate if the current page is equal to the total number of pages If it is true then we return false so that it does not make another request If false then we return the next page which is the result of the sum of the current page plus if currentPage lastPage info pages return false return currentPage And this is how the hook would look like import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppThe hook useInfiniteQuery gives us certain values and functions of which we will use the following data an object that contains the API query Inside this property there is another one called pages which is an array containing the obtained pages from here we will get the API data error An error message caused if the API request fails fetchNextPage function that allows to make a new request to the next API page status a string containing the values error loading success indicating the status of the request hasNextPage a boolean value that is true if the getNextPageParam function returns a value that is not undefined import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default App Showing the cards Now we can show the results thanks to the fact that we already have access to the data We create a div and inside we are going to make an iteration on the data property accessing to the page property that is an array that for the moment we will access to the first position and to the results In addition we evaluate the status and if it is loading we show the component Loading tsx but if it is in error we place the error message import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div className grid container gt data pages results map character gt lt Card key character id character character gt lt div gt lt div gt export default AppThis only shows the first page next we will implement infinite scroll Making the infinite scroll To do this we are going to use a popular library called react infinite scroll component We install the dependency npm i react infinite scroll componentFirst we need the InfiniteScroll component lt InfiniteScroll gt This component will receive several propertiesdataLength The number of elements in a moment we will put the value since we need to calculate it next a function that will be triggered when the end of the page is reached when scrolling Here we will call the function that useInfiniteQuery offers us fetchNextPage hasMore boolean property that indicates if there are more elements Here we will call the property offered by useInfiniteQuery hasNextPage and we convert it to boolean with because by default it is undefined loader JSX component that will be used to display a loading message while the request is being made Here we will call the Loading tsx component lt InfiniteScroll dataLength next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt Now the property dataLength we could but this would only show the next page without accumulating the previous results so we must do the following We will create a stored variable that will change every time the data property of useInfiniteQuery changes This characters variable must return a new ResponseAPI but the results property must accumulate the previous and current characters And the info property will be that of the current page const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data Now we pass this constant to dataLength we make an evaluation if the characters exists then we place the length of the property results if not we place lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt Now inside the component we must place the list to render like this Now instead of iterating over data pages results we are going to iterate over the memorized constant characters evaluating if it exists lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt And so everything would be complete import useMemo from react import InfiniteScroll from react infinite scroll component import useInfiniteQuery from tanstack react query import Loading from components Loading import Card from components Card import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt lt div gt export default AppAnd this is what it would look like Refactoring Let s create a new folder src hooks and add the useCharacter ts file And we move all the logic import useMemo from react import useInfiniteQuery from tanstack react query import ResponseAPI from interface export const useCharacter gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetch pageParam then res gt res json getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data return error fetchNextPage status hasNextPage characters Now in src App tsx it is easier to read import InfiniteScroll from react infinite scroll component import Loading from components Loading import Card from components Card import useCharacter from hooks useCharacter const App gt const characters error fetchNextPage hasNextPage status useCharacter if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt lt div gt export default App Conclusion The whole process I just showed is one of the ways you can implement infinite scroll in a fast way using third party packages ️I hope I helped you understand how to realize this design thank you very much for making it this far ️I invite you to comment if you find this article useful or interesting or if you know any other different or better way of how to implement an infinite scroll Live demo Source code Franklin infinite scroll Creating an infinite scroll with react js ️ Creating an infinite scroll with React JS ️This time we are going to implement the infinite scroll layout using React JS and other libraries Features ️View cards Load more cards while scrolling Technologies ️React JS version ️Vite JS ️TypeScript ️React Query ️Rick and Morty API ️CSS vanilla Los estilos los encuentras en el repositorio al final de este post Installation Clone the repository you need to have Git installed git clone Install dependencies of the project npm installRun the project npm run dev Links ️Demo of the application Here s the link to the tutorial in case you d like to take a look at it eyes View on GitHub |
2022-08-05 13:27:35 |
海外TECH |
DEV Community |
Creando un scroll infinito con React JS! ♾️ |
https://dev.to/franklin030601/creando-un-scroll-infinito-con-react-js-27gf
|
Creando un scroll infinito con React JS ️En esta ocasión vamos a implementar un scroll infinito usando React JS Una aplicación que implementa scroll infinito consiste en un diseño que permite a los usuarios seguir consumiendo cierta cantidad de información sin ninguna pausa ya que el contenido se va cargando automáticamente conforme el usuario vaya haciendo scroll Nota Este post requiere que sepas las bases de React con TypeScript hooks básicos Cualquier tipo de Feedback es bienvenido gracias y espero disfrutes el articulo Tabla de contenido Tecnologías a utilizar Creando el proyecto Primeros pasos Haciendo la petición a la API Mostrando las tarjetas Realizando el scroll infinito Refactorizando Conclusión Demostración en vivo Código fuente Tecnologías a utilizar ️React JS version ️Vite JS ️TypeScript ️React Query ️Rick and Morty API ️CSS vanilla Los estilos los encuentras en el repositorio al final de este post Creando el proyecto Al proyecto le colocaremos el nombre de infinite scroll opcional tu le puedes poner el nombre que gustes npm init vite latestCreamos el proyecto con Vite JS y seleccionamos React con TypeScript Luego ejecutamos el siguiente comando para navegar al directorio que se acaba de crear cd infinite scrollLuego instalamos las dependencias npm installDespués abrimos el proyecto en un editor de código en mi caso VS code code Primeros pasos Primero en el archivo src App tsx vamos a borrar el contenido y agregamos un titulo const App gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppLuego vamos a crear dos componentes que vamos a utilizar más tarde Creamos la carpeta src components y dentro creamos los siguientes archivos Loading tsxEste archivo contendrálo siguiente export const Loading gt return lt div className container loading gt lt div className spinner gt lt div gt lt span gt Loading more characters lt span gt lt div gt Nos servirápara mostrar un spinner cuando se haga una nueva petición a la API Card tsxEste archivo contendrálo siguiente import Result from interface interface Props character Result export const Card character Props gt return lt div className card gt lt img src character image alt character name width loading lazy gt lt p gt character name lt p gt lt div gt Esta es la tarjeta que mostrara el personaje de Rick and Morty APIEn la carpeta src interfaces creamos un archivo index ts y agregamos las siguientes interfaces export interface ResponseAPI info Info results Result export interface Info count number pages number next string prev string export interface Result id number name string image string Nota La interfaz Result en realidad tiene mas propiedades pero en este caso solo usare las que he definido Haciendo la petición a la API En este caso usaremos la librería React Query que nos va a permitir realizar las peticiones de una mejor forma y que ademas cuenta con otras características como manejo de caché Instalamos la dependencianpm i tanstack react queryY luego en el archivo src main tsx vamos hacer lo siguiente Vamos a encerrar nuestro componente App dentro del QueryClientProvider y le mandamos el cliente que es solamente una nueva instancia de QueryClient import QueryClient QueryClientProvider from tanstack react query import React from react import ReactDOM from react dom client import App from App import index css const queryClient new QueryClient ReactDOM createRoot document getElementById root as HTMLElement render lt React StrictMode gt lt QueryClientProvider client queryClient gt lt App gt lt QueryClientProvider gt lt React StrictMode gt Ahora en el archivo src App tsx vamos a usar un hook especial de React Query llamado useInfiniteQueryconst App gt useInfiniteQuery return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppEl hook useInfiniteQuery necesita varios parámetros queryKey un arreglo de strings u objetos anidados que se usa como clave para gestionar el almacenamiento del cache queryFn Una función que devuelve una promesa la promesa debe estar resuelta o lanzar un error options Dentro de las opciones necesitamos una que se llama getNextPageParam que es una función que devuelve la información para la siguiente consulta a la API El primer parámetro es la queryKey en este caso colocamos un arreglo con la palabra characters const App gt useInfiniteQuery characters return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppEl segundo parámetro es la queryFn en este caso colocamos un arreglo con la palabra characters Primero le pasamos una funciónconst App gt useInfiniteQuery characters gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppDicha función debe retornar una promesa resuelta Para ello fuera del componente creamos una función que recibirácomo parámetro la pagina a traer y retornara una promesa de tipo ResponseAPI import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters gt fetcher return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppLa queryFn recibe diversos parámetros entre ellos el pageParam que por defecto sera undefined y luego numero asi que si no existe un valor lo igualaremos a y dicha propiedad se la pasamos a la función fetcher import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppAhora el ultimo parámetro son las options que es un objeto el cual usaremos la propiedad getNextPageParamimport ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppLa función getNextPageParam recibe dos parámetros pero solo usaremos el primero que es la ultima pagina recibida o sea la ultima respuesta que nos dio la API Dentro de la función como la API de Rick and Morty no viene ña pagina siguiente mas bien viene la url para la pagina siguiente tendremos que realizar lo siguiente Obtendremos la pagina anteriorLa respuesta de la API viene la propiedad info que contiene la propiedad prev evaluamos si existe porque en la primera llamada la propiedad prev es null Si no existe entonces es la pagina Si existe entonces obtenemos esa cadena la separamos y obtenemos el número const previousPage lastPage info prev lastPage info prev split Obtendremos la pagina actualSolo sumamos la pagina anterior más const currentPage previousPage Evaluaremos si existen más paginasEvaluamos si la pagina actual es igual al total de paginas Si es true entonces retornamos false para que ya no haga otro petición Si es false entonces retornamos la siguiente pagina que es el resultado de la suma de la pagina actual mas if currentPage lastPage info pages return false return currentPage Y asi iría quedando el hook import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default AppEl hook useInfiniteQuery nos da ciertas valores y funciones de los cuales usaremos los siguientes data un objeto que contiene la consulta de la APIDentro de esta propiedad se encuentra otra llamada pages que es un arreglo que contiene las paginas obtenidas de aquíobtendremos la data de la API error Un mensaje de error causado si la petición a la API falla fetchNextPage función que permite realizar una nueva petición a la siguiente pagina de la API status una cadena que contiene los valores error loading success indicando el estado de la petición hasNextPage un valor booleano que es verdadero si la función getNextPageParam retorna un valor que no sea undefinedimport ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div gt export default App Mostrando las tarjetas Ahora podemos mostrar los resultados gracias a que ya tenemos acceso a la data Creamos un div y dentro vamos a hacer una iteración sobre la propiedad data accediendo a la propiedad page que es un arreglo que por el momento accederemos a la primera posición y a los results Ademas evaluamos el status y si es loading mostramos el componente Loading tsx pero si esta en error colocamos el mensaje de error import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt div className grid container gt data pages results map character gt lt Card key character id character character gt lt div gt lt div gt export default AppEsto solo muestra la primera pagina lo siguiente sera implementar el scroll infinito Realizando el scroll infinito Para ello vamos a usar una librería popular llamada react infinite scroll component Instalamos la dependencia npm i react infinite scroll componentPrimero necesitamos el componente InfiniteScroll lt InfiniteScroll gt Este componente recibirádiversos propiedadesdataLength La cantidad de elementos en un momento le colocaremos el valor ya que necesitamos calcularlo next una función que se disparara cuando se llegue al final de la pagina cuando se haga scroll Aquíllamaremos a la función que nos ofrece useInfiniteQuery fetchNextPage hasMore propiedad booleana que indica si hay más elementos Aquíllamaremos a la propiedad que nos ofrece useInfiniteQuery hasNextPage y lo convertimos en booleano con porque por defecto es undefined loader componente JSX que se usara para mostrar un mensaje de carga mientras se hace la petición Aquíllamaremos al componente Loading tsx lt InfiniteScroll dataLength next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt Ahora la propiedad dataLength podríamos pero esto solo mostraría la pagina siguiente sin acumularse los resultados anteriores por lo que debemos realizar lo siguiente Crearemos una variable memorizada que cambien cada vez que la propiedad data de useInfiniteQuery cambie Esta variable characters debe de retornar un nueva ResponseAPI pero el la propiedad de results se deben acumular los personajes anteriores y los actuales Y la propiedad info sera la de la pagina actual const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data Ahora le pasamos esta constante a dataLength hacemos una evaluación si existe los personajes entonces colocamos la longitud de la propiedad results sino colocamos lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt Ahora dentro del componente debemos colocar la lista a renderizar de esta manera Ahora en vez de iterar sobre data pages results vamos a iterar sobre la constante memorizada characters evaluando si existe lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt Y asi quedaría todo completo import useMemo from react import InfiniteScroll from react infinite scroll component import useInfiniteQuery from tanstack react query import Loading from components Loading import Card from components Card import ResponseAPI from interface const fetcher page number Promise lt ResponseAPI gt gt fetch page then res gt res json const App gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetcher pageParam getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt lt div gt export default AppY asi quedaría Refactorizando Vamos a crear una nueva carpeta src hooks y agregamos el archivo useCharacter tsY movemos toda la lógica import useMemo from react import useInfiniteQuery from tanstack react query import ResponseAPI from interface export const useCharacter gt const data error fetchNextPage status hasNextPage useInfiniteQuery characters pageParam gt fetch pageParam then res gt res json getNextPageParam lastPage ResponseAPI gt const previousPage lastPage info prev lastPage info prev split const currentPage previousPage if currentPage lastPage info pages return false return currentPage const characters useMemo gt data pages reduce prev page gt return info page info results prev results page results data return error fetchNextPage status hasNextPage characters Ahora en src App tsx es más fácil de leer import InfiniteScroll from react infinite scroll component import Loading from components Loading import Card from components Card import useCharacter from hooks useCharacter const App gt const characters error fetchNextPage hasNextPage status useCharacter if status loading return lt Loading gt if status error return lt h gt Ups error as string lt h gt return lt div gt lt h className title gt React Infinite Scroll lt h gt lt InfiniteScroll dataLength characters characters results length next gt fetchNextPage hasMore hasNextPage loader lt Loading gt gt lt div className grid container gt characters amp amp characters results map character gt lt Card key character id character character gt lt div gt lt InfiniteScroll gt lt div gt export default App Conclusión Todo el proceso que acabo de mostrar es una de las formas en que se puede implementar scroll infinito de una manera rápida usando paquetes de terceros ️Espero haberte ayudado a entender como realizar este diseño muchas gracias por llegar hasta aquí ️Te invito a que comentes si es que este articulo te resulta útil o interesante o si es que conoces alguna otra forma distinta o mejor de como implementar un scroll infinito Demostración en vivo Código fuente Franklin infinite scroll Creating an infinite scroll with react js ️ Creating an infinite scroll with React JS ️This time we are going to implement the infinite scroll layout using React JS and other libraries Features ️View cards Load more cards while scrolling Technologies ️React JS version ️Vite JS ️TypeScript ️React Query ️Rick and Morty API ️CSS vanilla Los estilos los encuentras en el repositorio al final de este post Installation Clone the repository you need to have Git installed git clone Install dependencies of the project npm installRun the project npm run dev Links ️Demo of the application Here s the link to the tutorial in case you d like to take a look at it eyes View on GitHub |
2022-08-05 13:27:03 |
海外TECH |
DEV Community |
Appwrite Community Report #17 |
https://dev.to/appwrite/appwrite-community-report-17-56g3
|
Appwrite Community Report Greetings from the Appwrite team We are back with our weekly updates This week we have some amazing announcements more details unfold inside Before we dive right into the report we extend our gratitude to the community and k star gazers on GitHub TLDR is released what are you building with it We also have Loot V announcements updated resources for better learning experience and more What s newWe just launched Loot V for our Discord Community Join in to grab some cool swags and hang out with the community What does it feel like to be a maintainer of an open source project Covering stories about OSS Fund sponsored maintainers Appwrite OSS Fund Sponsors InvenTree haimantika mitra for Appwrite・Aug ・ min read Can you relate to it Would some fund help you Appwrite OSS Fund is here to support Issues solvedWith our continued effort to make Appwrite the ultimate open source solution for all your backend needs here are some of the fixed we worked on Made the mock download endpoint response consistent with the rest of responsesLink to PRFixed docs storage and database linkLink to PRUpdated SDK Generator and CLI to the latest versionLink to PRFixed membership issue where information of person adding was returned instead of person being added by Fauzi E AbdulfattahLink to PR ️What we re currently working onAdding new metadata to API KeysAdding status codes to deployment objectFixes console SDKRefactoring tasks in Appwrite using the new Platform library DiscussionsLet s talk about Appwrite s permissions once moreJoin the discussion here ResourcesTutorial on Backing Up and Restoring on Appwrite ServerNetflix clone built with Appwrite and VueBuilding a Real Time Chat Application Using Appwrite and Angular Building a Realtime Chat Application Using Angular and Appwrite Brandon Roberts for Appwrite・Jun ・ min read angular appwrite webdev Learning Appwrite now made easy with the days challenge |
2022-08-05 13:18:07 |
Apple |
AppleInsider - Frontpage News |
Amazon buying iRobot in a $1.7 billion all-cash deal |
https://appleinsider.com/articles/22/08/05/amazon-to-acquire-irobot-in-a-17-billion-all-cash-deal?utm_medium=rss
|
Amazon buying iRobot in a billion all cash dealAmazon is set to acquire Roomba manufacturer iRobot in a deal valued at billion the two companies announced on Friday iRobot Roomba Credit Onur Binay UnsplashThe retail juggernaut will acquire iRobot for per share in an all cash deal Read more |
2022-08-05 13:40:11 |
Apple |
AppleInsider - Frontpage News |
Daily deals August 5: $100 off M2 MacBook Pro, Apple TV 4K for $120, $180 off Beats Studio3, more |
https://appleinsider.com/articles/22/08/05/daily-deals-august-5-100-off-m2-macbook-pro-apple-tv-4k-for-120-180-off-beats-studio3-more?utm_medium=rss
|
Daily deals August off M MacBook Pro Apple TV K for off Beats Studio moreFriday s best deals include a Netgear AC Dual Band Gigabit Wifi Router for off a PNY GeForce graphics card off an Insignia inch K TV and much more Best deals August On a daily basis AppleInsider checks online stores to uncover discounts on products including Apple hardware mobile devices hardware upgrades smart TVs and accessories The best offers are compiled into our daily deals post for you to enjoy Read more |
2022-08-05 13:15:55 |
Apple |
AppleInsider - Frontpage News |
iPadOS 16 delayed, iPhone 14 rumor roundup, and macOS utilities on the AppleInsider podcast |
https://appleinsider.com/articles/22/08/05/ipados-16-delayed-iphone-14-rumor-roundup-and-macos-utilities-on-the-appleinsider-podcast?utm_medium=rss
|
iPadOS delayed iPhone rumor roundup and macOS utilities on the AppleInsider podcastListener suggestions lead the AppleInsider podcast into a discussion about the bestmacOS utilities And while there s news that iPadOS is delayed there are more rumors about the iPhone and it s time to start the iOS wishlist Host Stephen Robles asked you for obscure Mac utilities you can t do without ーand you answered Hear all about tools for managing windows across several displays for using multiple browsers and a glimpse into the world of Read It Later apps and services In this week s news the biggest story is the claim that Apple may not release iPadOS alongside iOS as usual Instead it could delay the release until October ーwhich has everyone wondering whether that s tied to new iPad hardware coming out Read more |
2022-08-05 13:16:32 |
Apple |
AppleInsider - Frontpage News |
Satechi USB-C Slim Dock for 24-inch iMac review: a great way to add additional storage to your iMac |
https://appleinsider.com/articles/22/08/05/satechi-usb-c-slim-dock-for-24-inch-imac-review-a-great-way-to-add-additional-storage-to-your-imac?utm_medium=rss
|
Satechi USB C Slim Dock for inch iMac review a great way to add additional storage to your iMacSatechi s USB C Slim Dock gives your inch iMac most of the ports it was missing ーand an option for additional storage We love our inch iMac but there s one problem ーit only has rear facing ports making plugging in your devices difficult Additionally it features either two Thunderbolt ports or two Thunderbolt ports and two USB type C ports depending on which model you buy Unfortunately this means that legacy and specialty devices aren t compatible without a hub or a ton of adapters Read more |
2022-08-05 13:16:50 |
海外TECH |
Engadget |
Sony's LinkBuds S drop to a new low of $148 at Amazon |
https://www.engadget.com/sony-linkbuds-s-sale-lowest-price-amazon-134449867.html?src=rss
|
Sony x s LinkBuds S drop to a new low of at AmazonSony s LinkBuds S are now particularly tempting if you re looking for true wireless earbuds with a dash of intelligence Amazon is selling the LinkBuds S at a new low price of well below the usual That s even better than the Prime Day discount and could make them an easy choice if you want major brand audio without paying a stiff premium Buy LinkBuds S at Amazon The LinkBuds S signature feature is their smart playback They can automatically start or resume music based on your activity ーyou can specify a playlist when you go for a walk for instance They re also billed as the smallest and lightest wireless earbuds to support both active noise cancellation ANC and high resolution audio That s worth considering if comfort is paramount especially if you intend to listen for the claimed six hours per charge another hours is available through the case As the middle ground between the top tier WF XM and budget WF C the LinkBuds S involve some compromises The auto playback feature works for both Android and iOS users but it s limited to Spotify and the soundscape app Endel ANC isn t quite as powerful as it is in the WF XM and the case doesn t support wireless charging The sale price makes these omissions easier to forgive though and Sony has touted after launch upgrades like a low latency mode for gamers Follow EngadgetDeals on Twitter and subscribe to the Engadget Deals newsletter for the latest tech deals and buying advice |
2022-08-05 13:44:49 |
海外TECH |
Engadget |
Samsung’s Z Fold 3 durability one year in: Tougher than you might think, but with one big caveat |
https://www.engadget.com/z-fold-3-long-term-durability-report-heres-what-samsung-still-cant-get-right-130053466.html?src=rss
|
Samsung s Z Fold durability one year in Tougher than you might think but with one big caveatFoldable phones are still kind of awkward unproven devices But over the last three generations with a fourth presumably on the way Samsung has made major strides with its designs paving the way for innovative though sometimes quite pricey alternatives to the typical glass brick And when you combine that with sales of nearing million devices last year it feels like Samsung s foldables are finally beginning to break into the mainstream But despite a number of improvements over the years there s one aspect of Samsung s foldable that still needs a lot of work durability Last year after purchasing my own Z Fold I documented some of the issues I faced after owning it for months And after upgrading to the Z Fold last fall I m here to report back on how Samsung s latest flagship foldable is holding up just shy of one year later Aside from one scratch at the bottom which I take sole blame for my Galaxy Z Fold s exterior Cover Screen is still almost pristine Sam Rutherford EngadgetNow at this point some people might be wondering why I upgraded at all The bubbles my Z Fold s screen suffered from were certainly annoying but they weren t so bad I considered switching back to a standard candy bar handset Instead my main goal for buying the model aside from professional curiosity was to get a foldable that might better survive a newborn Compared to typical smartphones the Z Fold s lack of water resistance was all but guaranteed to become a problem after my son was born It felt like I would have to keep the phone in a separate room lest I chance some small amount of spit up or drool ruining the device And that simply wasn t something I wanted to do which is what drew me to the Z Fold and its IPX rating I figured if a phone can withstand sitting in water for up to minutes at a depth of up to five feet it could handle anything a baby could throw or spit at it too The back of the phone has also held up very well aside from one ding on the edge of the frame Sam Rutherford EngadgetThankfully I think my strategy worked because even though it cost around to upgrade after trading in my Z Fold that money has already paid for itself My Z Fold has been peed on it s been vomited on and it s had milk splashed all over it and it s been totally fine The phone has also been gnawed on more than a handful of times to no effect So while the addition of water resistance to Samsung s foldables might not be all that exciting considering regular phones that have had it for years it s a huge enhancement to everyday usability The rest of the phone s body has held up pretty well too There s a relatively large scratch on its frame and a couple of scuffs on its hinge but those are all cosmetic dings I should also mention I m not someone who puts phones in skins or cases this thing has lived naked since the day I got it So while I haven t been traveling much the sheer number of times this phone has endured being knocked out of my hand or fallen on the floor while rushing to grab my kid after a nap is kind of impressive Even dust and crumbs have been handled by the extra bristles Samsung put inside its hinge There are also some small scuffs on the hinge but that s sort of to be expected considering I never put the phone in a case Sam Rutherford EngadgetThe big exception to the Z Fold s improved durability is once again its built in screen protector For this model Samsung says it switched away from the TPU material it used on the Z Fold to a new PET film while also using a stickier adhesive which was designed to prevent bubbles from forming between the protector and the display itself But in my experience none of that helped For the first six months I had it my Z Fold s screen was pristine There were no blemishes bubbles or anything But then one winter day while I was walking down the street I opened the phone and heard a crack At first I feared the worst thinking its exterior cover screen had shattered or something important inside had broken But upon closer inspection I noticed there was a fine line running down the middle of the phone near the crease as if the protector had been pulled or stretched This is what the bubbling looked like in June when I first attempted to get it repaired Sam Rutherford EngadgetAnd while I m still not sure what the exact cause was my theory is that after pulling the phone out of my pocket the cold winter air made the screen protector unusually brittle causing it to snap instead of bend when I opened the phone This is an issue a number of other Z Fold owners have run into and once you suffer that initial crack it s only a matter of time until bubbles begin to form Over the past few months those bubbles have grown into an air gap that runs down the entire middle of the screen and no amount of pressing or trying smoothing things out has much of an effect Recently some dust has gotten wedged between the protector and the screen itself which is frankly kind of gross And because I m trying to abide by Samsung s insistence that the screen protector should only be replaced by certified technicians I haven t tried to fix it on my own Naturally the next step was to take the phone to one of Samsung s retail locations to have it serviced at which point I discovered I m far from the only person dealing with this When I arrived there were three other people already on the waitlist ーand all of them were waiting to get the screen protector on their Z Fold replaced Admittedly this is merely an anecdotal observation and I m sure my choice to go to Samsung s flagship location in NYC had something to do with the unusually high concentration of foldable phones This close up shot shows how gross the display can get because once bubbles start forming there isn t much you can do to stop dust and first from getting beneath the screen protector Sam Rutherford EngadgetBut this wasn t a coincidence either After talking to two of the other customers I learned that they were also running into issues with bubbles around the six to eight month mark On top of that one of the Samsung Care reps I talked to essentially confirmed that this was a somewhat widespread issue saying that screen protector replacements are the most commonly requested repair for Samsung s foldables Unfortunately because it takes about an hour to have the screen protector replaced and I was fourth in line I couldn t wait around to get my Z Fold fixed So here s a pro tip if your phone needs to be serviced make sure to schedule your appointment online so you can avoid the line In the end while I plan on returning to have my screen protector replaced my big take away after owning both a Z Fold and a Z Fold is that there s a good chance you re going to run into bubbles after half a year or so And without some sort of radical upgrade to the screen construction the company s next generation of Z devices will probably suffer the same fate That s kind of a bummer because having to sit around for hours to fix something that s probably going to happen again sucks And that goes double or triple for anyone who has to mail in their device because they don t live near a certified repair location This is how my Z Fold s screen looks after one year The bubble now covers the entire height of the display And while its appearance is more tolerable indoors it s still far from ideal Sam Rutherford EngadgetAs it stands the bubbling is certainly annoying and not very pretty Thankfully the side effects are much less noticeable indoors or at night so while it s far from ideal it s tolerable I will also admit that had I not been planning on writing this story I would have gotten the screen protector replaced months ago And if you re running into a similar issue with your Z Flip or Z Fold I d highly suggest you address any bubbling as soon as possible before any other related issues pop up But if Samsung ever wants its foldables to be as popular as the S or A series phones the screen protectors bubbling is an issue that needs to be solved sooner rather than later As for me while I haven t decided if I want to upgrade again or not I m just hoping that anyone on the fence will now have a slightly more realistic idea of what living with a foldable phone is actually like |
2022-08-05 13:00:53 |
海外科学 |
NYT > Science |
A Large Object Landed on His Sheep Farm. It Came From Space. |
https://www.nytimes.com/2022/08/04/world/australia/spacex-debris-australia.html
|
A Large Object Landed on His Sheep Farm It Came From Space “It s not something you see every day on a sheep farm a farmer said of the pieces of debris that wound up in rural Australia They are thought to be from a SpaceX spacecraft |
2022-08-05 13:20:44 |
海外科学 |
NYT > Science |
How Republicans Are ‘Weaponizing’ Public Office Against Climate Action |
https://www.nytimes.com/2022/08/05/climate/republican-treasurers-climate-change.html
|
How Republicans Are Weaponizing Public Office Against Climate ActionA Times investigation revealed a coordinated effort by state treasurers to use government muscle and public funds to punish companies trying to reduce greenhouse gases |
2022-08-05 13:03:32 |
金融 |
RSS FILE - 日本証券業協会 |
新型コロナウイルス感染症への証券関係機関等・各証券会社の対応について(リンク集) |
https://www.jsda.or.jp/shinchaku/coronavirus/link.html
|
新型コロナウイルス |
2022-08-05 14:10:00 |
金融 |
金融庁ホームページ |
「店頭デリバティブ取引等の規制に関する内閣府令の一部を改正する内閣府令(案)」及び「店頭デリバティブ取引等の規制に関する内閣府令第三条の二第四号及び第七条の二第四号の規定に基づき、その他やむを得ない理由として金融庁長官が定めるものを次のように定める件」の一部改正(案)に対するパブリックコメントの結果等について公表しました。 |
https://www.fsa.go.jp/news/r4/shouken/20220805/20220805.html
|
内閣府令 |
2022-08-05 15:00:00 |
ニュース |
BBC News - Home |
Archie Battersbee: Family refused permission for hospice move |
https://www.bbc.co.uk/news/uk-england-essex-62424659?at_medium=RSS&at_campaign=KARANGA
|
archie |
2022-08-05 13:15:30 |
ニュース |
BBC News - Home |
Alex Belfield trial: Former BBC presenter found guilty of stalking |
https://www.bbc.co.uk/news/uk-england-nottinghamshire-62393949?at_medium=RSS&at_campaign=KARANGA
|
online |
2022-08-05 13:46:01 |
ニュース |
BBC News - Home |
Mont Blanc climbers to pay €15,000 rescue deposit |
https://www.bbc.co.uk/news/world-europe-62436466?at_medium=RSS&at_campaign=KARANGA
|
costs |
2022-08-05 13:38:11 |
ニュース |
BBC News - Home |
Commonwealth Games: George Miller becomes oldest medallist as Scotland win bowls gold |
https://www.bbc.co.uk/sport/commonwealth-games/62435257?at_medium=RSS&at_campaign=KARANGA
|
Commonwealth Games George Miller becomes oldest medallist as Scotland win bowls goldGeorge Miller becomes the oldest Commonwealth Games gold medallist as Scotland defeat Wales in the final of the B B mixed pairs bowls |
2022-08-05 13:31:52 |
ニュース |
BBC News - Home |
Eddie Howe: Newcastle United manager signs new long-term contract |
https://www.bbc.co.uk/sport/football/62432687?at_medium=RSS&at_campaign=KARANGA
|
contract |
2022-08-05 13:41:47 |
北海道 |
北海道新聞 |
米就業者52万人増に拡大 失業率3・5%、コロナ前に改善 |
https://www.hokkaido-np.co.jp/article/714812/
|
雇用統計 |
2022-08-05 22:29:00 |
北海道 |
北海道新聞 |
ソ7―3楽(5日) ソフトバンクが2位浮上 |
https://www.hokkaido-np.co.jp/article/714809/
|
適時 |
2022-08-05 22:23:00 |
北海道 |
北海道新聞 |
道央道でクマと乗用車衝突 別の1頭も出没、4時間超通行止め |
https://www.hokkaido-np.co.jp/article/714805/
|
苫小牧市樽前 |
2022-08-05 22:14:00 |
北海道 |
北海道新聞 |
70代男性が700万円だまし取られる 札幌 |
https://www.hokkaido-np.co.jp/article/714803/
|
札幌市南区 |
2022-08-05 22:09:00 |
北海道 |
北海道新聞 |
日米と中ロ、台湾巡り対立鮮明 東アジアサミット外相会議 |
https://www.hokkaido-np.co.jp/article/714799/
|
外相会議 |
2022-08-05 22:05:00 |
北海道 |
北海道新聞 |
JR北海道、営業赤字127億円に縮小 4~6月期連結決算 観光回復で改善、純損益は黒字 |
https://www.hokkaido-np.co.jp/article/714787/
|
連結決算 |
2022-08-05 22:03:16 |
コメント
コメントを投稿