投稿時間:2022-06-24 07:17:31 RSSフィード2022-06-24 07:00 分まとめ(21件)

カテゴリー等 サイト名等 記事タイトル・トレンドワード等 リンクURL 頻出ワード・要約等/検索ボリューム 登録日
IT ITmedia 総合記事一覧 [ITmedia ビジネスオンライン] 動画サブスク、4割弱が“掛け持ち” テレビ視聴ユーザーは年々減少 https://www.itmedia.co.jp/business/articles/2206/23/news108.html 浮き彫り 2022-06-24 06:30:00
Google カグア!Google Analytics 活用塾:事例や使い方 オンライン授業に元教員おすすめの本16冊とリモート指導方法 https://www.kagua.biz/review/book/online-classroom-book.html moodle 2022-06-23 21:00:17
js JavaScriptタグが付けられた新着投稿 - Qiita Reactの弊害。自動テストのスクリプトを阻むステート管理を無理やり突破 https://qiita.com/taukuma/items/994127bda00f7f231ac4 react 2022-06-24 06:58:55
AWS AWSタグが付けられた新着投稿 - Qiita セッションマネージャを使ってECインスタンスへアクセスする https://qiita.com/hikotaro_san/items/06b3ef23cbe755143410 awssystemsmanager 2022-06-24 06:41:25
技術ブログ Developers.IO CloudWatch で QuickSightのメトリクスが利用できるようになりました https://dev.classmethod.jp/articles/cloudwatch-quicksight-metrics/ cloudwatch 2022-06-23 21:30:22
海外TECH MakeUseOf How to Get Started With Any Project Management Software https://www.makeuseof.com/get-started-any-project-management-software/ management 2022-06-23 21:30:14
海外TECH MakeUseOf 10 Great Healthy Eating Podcasts Worth Listening To https://www.makeuseof.com/best-healthy-eating-podcasts/ happy 2022-06-23 21:01:16
海外TECH DEV Community ¿Cómo crear un buscador con efecto "debounce"? 🔎 https://dev.to/franklin030601/como-crear-un-buscador-con-efecto-debounce-4jcp ¿Cómo crear un buscador con efecto quot debounce quot Tabla de contenidoIntroducción Tecnologías a utilizar ¿Quées el efecto Debounce Creando el proyecto Primeros pasos Creando el input Manejando el estado del input Creando la función para la petición a la API Creando el efecto Debounce Haciendo la llamada a la API Creando el componente Pokemon tsx Usando nuestro componente Pokemon Limpiando la lógica de nuestro componente Manejando la lógica para controlar el input Manejando la lógica para la llamada a la API Manejando la lógica para el efecto Debounce Conclusión Código fuente   Introducción El propósito de este post es enseñar una manera sencilla de como realizar un pequeño buscador con un efecto debounce Dicho proyecto puede extenderse de muchas maneras pero tratare de hacerlo algo básico pero eficiente Nota Este post requiere que sepas las bases de React con TypeScript hooks básicos y peticiones con fetch Cualquier tipo de Feedback es bienvenido gracias y espero disfrutes el articulo   Tecnologías a utilizar ️React JS version ️Vite JS ️TypeScript ️Pokemon API ️CSS vanilla Los estilos los encuentras en el repositorio al final de este post   ¿Quées el efecto Debounce El efecto rebote debounce es cuando no se ejecutan al momento de su invocación En lugar de eso su ejecución es retrasada por un periodo predeterminado de tiempo Si la misma función es invocada de nuevo la ejecución previa es cancelada y el tiempo de espera se reinicia   Creando el proyecto Al proyecto le colocaremos el nombre de search debounce 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 search debounceLuego instalamos las dependencias npm installDespués abrimos el proyecto en un editor de código en mi caso VS code code   Primeros pasos Dentro de la carpeta src App tsx borramos todo el contenido del archivo y colocamos un componente funcional que muestre un titulo const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt div gt export default AppDebería de verse así   Creando el input Ahora creamos la carpeta src components y dentro de la carpeta creamos el archivo Input tsx y dentro agregamos lo siguiente export const Input gt return lt gt lt label htmlFor pokemon gt Name or ID of a Pokemon lt label gt lt input type text id pokemon placeholder Example Pikachu gt lt gt Una vez hecho lo importamos en el archivo App tsximport Input from components Input const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input gt lt div gt export default AppDebería de verse así   Manejando el estado del input Nota Esta NO es la única forma para realizar este ejercicio solo es una opción Si tienes una mejor manera me gustaría que la compartieras por los comentarios por favor En este caso voy a manejar el estado del input en un nivel superior o sea el componente App del archivo App tsxEsto lo haremos debido a que necesitamos el valor del input disponible en App tsx ya que ahi se harála petición a la API y el efecto debounce Primero creamos el estado para manejar el valor del input const value setValue useState Creamos una función para que actualice el estado del input cuando el input haga un cambio Esta función recibe como parámetro el evento que emite el input de dicho evento obtendremos la propiedad target y luego la propiedad value la cual es la que mandaremos a nuestro estado const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value Por consiguiente toca mandar la función y el valor del estado al input const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App En el componente Input agregamos una interfaz para recibir las propiedades por parámetro en el archivo Input tsx interface Props value string onChange e React ChangeEvent lt HTMLInputElement gt gt void Desestructuramos las propiedades y las agregamos al input La función onChange la colocamos en la propiedad onChange del input y lo mismo con el la value propiedad value interface Props value string onChange e React ChangeEvent lt HTMLInputElement gt gt void export const Form onChange value Props gt return lt gt lt label htmlFor pokemon gt Name of a Pokemon lt label gt lt input type text id pokemon placeholder Example Pikachu value value onChange onChange gt lt gt Y asíya tenemos controlado el estado de nuestro input   Creando la función para la petición a la API Ahora creamos la carpeta src utils y dentro colocamos un archivo llamado searchPokemon ts y agregamos la siguiente función para hacer la petición y buscar un pokemon por su nombre o ID Nota La respuesta de la API tiene más propiedades de las que se representa en la interfaz ResponseAPIEsta función recibe dos parámetros pokemon es el nombre o ID del pokemon signal permite establecer escuchadores de eventos En otras palabras nos ayudara a cancelar la petición HTTP cuando el componente se desmonte o haga un cambio en el estado Esta función retorna la data del pokemon si todo sale bien o null si algo sale mal export interface ResponseAPI name string sprites front default string export const searchPokemon async pokemon string signal AbortSignal Promise lt ResponseAPI null gt gt try const url pokemon toLowerCase trim const res await fetch url signal if res status return null const data ResponseAPI await res json return data catch error console log error as Error message return null   Creando el efecto Debounce En el archivo App tsx creamos un estado que nos servirápara guardar el valor del input const debouncedValue setDebouncedValue useState Como estado inicial le mandamos el valor del estado del input value const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value Ahora creamos un efecto para que cuando el valor del input cambie ejecutamos la función setTimeout que actualizara el estado del debouncedValue enviando el nuevo valor del input después de segundo y asi obtendremos la palabra clave o sea el pokemon para hacer la petición a la API Al final del efecto ejecutamos el método de limpieza que consiste en limpiar la función setTimeout es por eso que la guardamos en una constante llamada timeruseEffect gt const timer setTimeout gt setDebouncedValue value return gt clearTimeout timer value Entonces por el momento nuestro archivo App tsx quedaría de la siguiente manera import useEffect useState from react import Input from components Input const App gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App  Haciendo la llamada a la API Una vez que tenemos el valor del input ya con el efecto debounce toca hacer la llamada a la API Para eso usaremos al función que creamos con anterioridad searchPokemon tsx Para ello vamos a usar un efecto Primero creamos el controller el cual es el que nos ayudara a cancelar la petición HTTP como mencionamos antesDentro del controller tenemos dos propiedades que nos interesan abort al ejecutarse cancela la petición signal mantiene la conexión entre el controller y el la petición para saber cual se debe cancelar El abort lo ejecutamos al final al momento de que se desmonte el componente useEffect gt const controller new AbortController return gt controller abort La dependencia de este efecto sera el valor del debouncedValue ya que cada vez que cambie este valor debemos hacer una nueva petición para buscar al nuevo pokemon useEffect gt const controller new AbortController return gt controller abort debouncedValue Hacemos una condición en la que solo si el existe el valor de debouncedValue y tiene alguna palabra o numero haremos la petición useEffect gt const controller new AbortController if debouncedValue return gt controller abort debouncedValue Dentro del if llamamos la función de searchPokemon y le mandamos el valor de debouncedValue y también la propiedad signal del controlleruseEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal return gt controller abort debouncedValue Y como la función searchPokemon regresa una promesa y dentro del efecto no es permitido usar async await usaremos then para resolver la promesa y obtener el valor que retorna useEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal then data gt console log data pokemon null return gt controller abort debouncedValue Al final debería de verse asi import useEffect useState from react import Input from components Input import searchPokemon from utils searchPokemon const App gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal then data gt console log data pokemon null return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App  Creando el componente Pokemon tsx Primero creamos el componente funcional vació export const Pokemon gt return lt gt lt gt Agregamos la interfaz de ResponseAPI ya que vamos a recibir por props el pokemon el cual puede contener la data del pokemon o un valor nulo import ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt return lt gt lt gt Hacemos una evaluación donde Si el la propiedad pokemon es nula mostramos el mensaje de No results Si la propiedad pokemon contiene la data del pokemon mostramos su nombre y una imagenimport ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt return lt gt pokemon lt span gt No results lt span gt lt div gt lt h gt pokemon name lt h gt lt img src pokemon sprites front default alt pokemon name gt lt div gt lt gt Debería de verse asi si esta cargando Debería de verse asi cuando no hay resultados Debería de verse asi hay un pokemon Y ahora por ultimo agregamos una ultima condición en donde evaluamos si el pokemon existe o sea que no es nula y si es un objeto vacióretornamos un fragmento Esto es asíya que el estado inicial para almacenar a los pokemon sera un objeto vacío Si no colocaremos esa condición entonces la inicio de nuestra app incluso sin haber tecleado nada en el input ya nos aparecería el mensaje de No results y la idea es que aparezca después de que hayamos tecleado algo en el input y se haya hecho la llamada a la API import ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt if pokemon amp amp Object keys pokemon length return lt gt lt gt return lt gt pokemon lt span gt No results lt span gt lt div gt lt h gt pokemon name lt h gt lt img src pokemon sprites front default alt pokemon name gt lt div gt lt gt Asi quedaría nuestro componente pokemon es hora de usarlo   Usando nuestro componente Pokemon En el archivo App tsx agregaremos nuevos estados Para almacenar el pokemon encontrado que tendráun valor inicial de un objeto vacío Para manejar un loading en lo que se hace la llamada a la API que tendráun valor inicial de falso const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false Ahora dentro del efecto donde hacemos la llamada a la API mediante la función searchPokemon antes de hacer la llamada enviamos el valor de true al setIsLoading para activar el loading Después una vez obtenida la data dentro del then le enviamos dicha data al setPokemon el cual puede ser el pokemon o un valor nulo Y finalmente enviamos el valor de false al setIsLoading para quitar el loading useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue Una vez almacenado el pokemon en el JSX colocamos la siguiente condición Si el valor del estado isLoading es verdadero mostramos el mensaje de Loading Results Si el valor del estado isLoading es falso mostramos el componente Pokemon mandándole el pokemon return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt Y todo junto quedaría asi import useEffect useState from react import Input from components Input import Pokemon from components Pokemon import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default AppEs mucha lógica en un solo componente cierto Ahora nos toca refactorizar   Limpiando la lógica de nuestro componente Tenemos mucha lógica en nuestro componente por lo que es necesario separarla en diversos archivos Lógica para controlar el input Lógica del debounce Lógica para hacer la llamada a la API y manejar el pokemon Y como esta lógica hace uso de hooks como es useState y useEffect entonces debemos colocarlos en un custom hook Lo primero sera crear una nueva carpeta src hooks Manejando la lógica para controlar el input Dentro de la carpeta src hooks creamos el siguiente archivo useInput tsY colocamos la lógica correspondiente al manejo del input import useState from react export const useInput string e React ChangeEvent lt HTMLInputElement gt gt void gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value return value onChange Luego llamamos al useInput en el archivo App tsximport useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default App  Manejando la lógica para la llamada a la API Dentro de la carpeta src hooks creamos el siguiente archivo useSearchPokemon ts Colocamos la lógica relacionada con hacer la petición a la API y mostrar el pokemon Este custom hook recibe como parámetro un string llamado search que es el nombre del pokemon o el ID Y ese parámetro se lo enviamos a la función que hace la llamada a la API searchPokemonNota Observe la parte del If en el efecto al final colocamos un else donde si el debouncedValue esta vació nno haremos una llamada a la API y le mandamos el valor de un objeto vacióa setPokemonimport useState useEffect from react import ResponseAPI from interface pokemon import searchPokemon from utils searchPokemon export const useSearchPokemon search string gt const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false useEffect gt const controller new AbortController if search setIsLoading true searchPokemon search controller signal then data gt setPokemon data setIsLoading false else setPokemon as ResponseAPI return gt controller abort search return pokemon isLoading Luego llamamos al useSearchPokemon en el archivo App tsximport useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import useSearchPokemon from hooks useSearchPokemon import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const debouncedValue setDebouncedValue useState value const isLoading pokemon useSearchPokemon debouncedValue useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default App  Manejando la lógica para el efecto Debounce Dentro de la carpeta src hooks creamos el siguiente archivo useDebounce ts y colocamos toda la lógica para manejar el efecto debounce Este custom hook recibe parámetros value es el valor del estado del input delay es la cantidad de tiempo que quieres retrasar la ejecución del debounce y es opcional Nota la propiedad delay la usamos el segundo parámetro de la función setTimeout donde en caso de que delay sea undefined entonces el tiempo por defecto sera ms Y también agregamos la propiedad delay al arreglo de dependencias del efecto import useState useEffect from react export const useDebounce value string delay number gt const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return debouncedValue Luego llamamos al useDebounce en el archivo App tsximport useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import useSearchPokemon from hooks useSearchPokemon import useDebounce from hooks useDebounce import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const debouncedValue useDebounce value const isLoading pokemon useSearchPokemon debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default AppY asi nuestro componente App tsx quedo mas limpio y fácil de leer   Conclusión Todo el proceso que acabo de mostrar es una de las formas en que se puede hacer un buscador con efecto debounce Espero haberte ayudado a entender como realizar este ejercicio muchas gracias por llegar hasta aquí Te invito a que comentes si es que conoces alguna otra forma distinta o mejor de como hacer un efecto debounce para un buscador   Código fuente Franklin search engine debounce effect Creating a search engine with debounce effect with React JS Search Engine Debounce Effect Creating a search engine with debounce effect with React JS and Pokemon API Technologies React JSTypescriptVite JSInstalation Clone the repository git clone Run this command to install the dependencies npm install Run this command to raise the development server npm run devLinks ️Demo of the app Link to tutorial post How to make a search engine with debounde effect View on GitHub 2022-06-23 21:12:28
海外TECH DEV Community How to create a search engine with "debounce effect"? 🔎 https://dev.to/franklin030601/how-to-create-a-search-engine-with-debounce-effect-4hef How to create a search engine with quot debounce effect quot Table of contents Introduction Technologies to be used What is the Debounce effect Creating the project First steps Creating the input Handling the input status Creating the function for the API request Creating the Debounce effect Making the API call Creating the Pokemon tsx component Using our Pokemon component Cleaning the logic of our component Handling the logic to control the input Handling the logic for the API call Handling the logic for the Debounce effect Conclusion Source code   Introduction The purpose of this post is to show a simple way on how to make a small search engine with a debounce effect Such a project can be extended in many ways but I will try to make it something basic but efficient Note This post requires you to know the basics of React with TypeScript basic hooks and fetch requests Any kind of Feedback is welcome thanks and I hope you enjoy the article   Technologies to be used ️React JS version ️Vite JS ️TypeScript ️Pokemon API ️Vanilla CSS You can find the styles in the repository at the end of this post   What is the Debounce effect The debounce effect is when they are not executed at the time of their invocation Instead their execution is delayed for a predetermined period of time If the same function is invoked again the previous execution is cancelled and the timeout is restarted   Creating the project We will name the project search debounce 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 execute the following command to navigate to the directory just created cd search debounceThen we install the dependencies npm installThen we open the project in a code editor in my case VS code code   First steps Inside the folder src App tsx we delete all the contents of the file and place a functional component that displays a title const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt div gt export default AppIt should look like this   Creating the input Now we create the folder src components and inside the folder we create the file Input tsx and inside we add the following export const Input gt return lt gt lt label htmlFor pokemon gt Name or ID of a Pokemon lt label gt lt input type text id pokemon placeholder Example Pikachu gt lt gt Once done we import it into the App tsx file import Input from components Input const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input gt lt div gt export default AppIt should look like this   Handling the input status Note This is NOT the only way to perform this exercise it is only one option If you have a better way I would like you to share it in the comments please In this case I am going to handle the input status at a higher level i e the App component of the App tsx file We will do this because we need the value of the input available in App tsx since the request to the API and the debounce effect will be made there First we create the state to handle the value of the input const value setValue useState We create a function to update the state of the input when the input makes a change This function receives as parameter the event that emits the input of this event we will obtain the property target and then the property value which is the one that we will send to our state const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value Therefore it is time to send the function and the value of the status to the input const App gt return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App In the Input component we add an interface to receive the properties by parameter in the Input tsx file interface Props value string onChange e React ChangeEvent lt HTMLInputElement gt gt void We unstructure the properties and add them to the input The onChange function we place it in the onChange property of the input and the same with the value property value interface Props value string onChange e React ChangeEvent lt HTMLInputElement gt gt void export const Form onChange value Props gt return lt gt lt label htmlFor pokemon gt Name of a Pokemon lt label gt lt input type text id pokemon placeholder Example Pikachu value value onChange onChange gt lt gt And so we already have the status of our input under control   Creating the function for the API request Now we create the src utils folder and inside we place a file called searchPokemon ts and add the following function to make the request and search for a pokemon by its name or ID Note The API response has more properties than what is represented in the ResponseAPI interface This function receives two parameters pokemon is the name or ID of the pokemon signal allows to set event listeners In other words it will help us to cancel the HTTP request when the component is unmounted or makes a change in the state This function returns the pokemon data if everything goes well or null if something goes wrong export interface ResponseAPI name string sprites front default string export const searchPokemon async pokemon string signal AbortSignal Promise lt ResponseAPI null gt gt try const url pokemon toLowerCase trim const res await fetch url signal if res status return null const data ResponseAPI await res json return data catch error console log error as Error message return null   Creating the Debounce effect In the App tsx file we create a state which will be used to store the value of the input const debouncedValue setDebouncedValue useState As initial state we send the value of the input state value const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value Now we create an effect so that when the value of the input changes we execute the setTimeout function that will update the state of the debouncedValue sending the new value of the input after second and thus we will obtain the keyword or the pokemon to make the request to the API At the end of the effect we execute the cleaning method which consists of cleaning the setTimeout function that is why we store it in a constant called timer useEffect gt const timer setTimeout gt setDebouncedValue value return gt clearTimeout timer value So for the moment our App tsx file would look like this import useEffect useState from react import Input from components Input const App gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App  Making the API call Once we have the value of the input already with the debounce effect it is time to make the API call For that we will use the function that we created previously searchPokemon tsx For it we are going to use an effect First we create the controller which is the one that will help us to cancel the HTTP request as we mentioned before Inside the controller we have two properties that interest us abort when executed cancels the request signal maintains the connection between the controller and the request to know which one to cancel The abort is executed at the end when the component is unmounted useEffect gt const controller new AbortController return gt controller abort The dependency of this effect will be the value of the debouncedValue since every time this value changes we must make a new request to search for the new pokemon useEffect gt const controller new AbortController return gt controller abort debouncedValue We make a condition in which only if the debouncedValue exists and has some word or number we will make the request useEffect gt const controller new AbortController if debouncedValue return gt controller abort debouncedValue Inside the if we call the searchPokemon function and send it the value of debouncedValue and also the signal property of the controller useEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal return gt controller abort debouncedValue And since the searchPokemon function returns a promise and within the effect it is not allowed to use async await we will use then to resolve the promise and get the value it returns useEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal then data gt console log data pokemon null return gt controller abort debouncedValue In the end it should look like this import useEffect useState from react import Input from components Input import searchPokemon from utils searchPokemon const App gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue searchPokemon debouncedValue controller signal then data gt console log data pokemon null return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt lt div gt export default App  Creating the Pokemon tsx component First we create the empty functional component export const Pokemon gt return lt gt lt gt We add the ResponseAPI interface since we are going to receive by props the pokemon which can contain the pokemon data or a null value import ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt return lt gt lt gt We make an evaluation where If the pokemon property is null we show the No results message If the pokemon property contains the pokemon data we show its name and an image import ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt return lt gt pokemon lt span gt No results lt span gt lt div gt lt h gt pokemon name lt h gt lt img src pokemon sprites front default alt pokemon name gt lt div gt lt gt It should look like this if it is loading It should look like this when there are no results It should look like this there is a pokemon And now finally we add a last condition where we evaluate if the pokemon exists i e it is not null and if it is an empty object we return a fragment This is because the initial state for storing pokemon will be an empty object If we don t put that condition then at the start of our app even without having typed anything in the input the No results message will appear and the idea is that it will appear after we have typed something in the input and the API call has been made import ResponseAPI from utils searchPokemon export const Pokemon pokemon pokemon ResponseAPI null gt if pokemon amp amp Object keys pokemon length return lt gt lt gt return lt gt pokemon lt span gt No results lt span gt lt div gt lt h gt pokemon name lt h gt lt img src pokemon sprites front default alt pokemon name gt lt div gt lt gt This is how our pokemon component would look like it s time to use it   Using our Pokemon component In the App tsx file we will add new states To store the pokemon found which will have an initial value of an empty object To handle a loading on what the API call is made which will have an initial value of false const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false Now inside the effect where we make the call to the API through the function searchPokemon before making the call we send the value of true to the setIsLoading to activate the loading Then once we get the data inside the then we send the data to the setPokemon which can be the pokemon or a null value And finally we send the value of false to setIsLoading to remove the loading useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue Once the pokemon is stored in the JSX we place the following condition If the value of the isLoading status is true we display the Loading Results message If the value of the isLoading status is false we show the Pokemon component sending it the pokemon return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt And everything together would look like this import useEffect useState from react import Input from components Input import Pokemon from components Pokemon import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default AppThat s a lot of logic in one component right Now it s our turn to refactor   Cleaning the logic of our component We have a lot of logic in our component so it is necessary to separate it into several files Logic to control the input Debounce logic Logic to make the API call and handle the pokemon And as this logic makes use of hooks like useState and useEffect then we must place them in a custom hook The first thing will be to create a new folder src hooks Handling the logic to control the input Inside the folder src hooks we create the following file useInput ts And we place the logic corresponding to the handling of the input import useState from react export const useInput string e React ChangeEvent lt HTMLInputElement gt gt void gt const value setValue useState const onChange e React ChangeEvent lt HTMLInputElement gt gt setValue e target value return value onChange Then we call useInput in the App tsx file import useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay useEffect gt const controller new AbortController if debouncedValue setIsLoading true searchPokemon debouncedValue controller signal then data gt setPokemon data setIsLoading false return gt controller abort debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default App  Handling the logic for the API call Inside the folder src hooks we create the following file useSearchPokemon ts We place the logic related to make the request to the API and show the pokemon This custom hook receives as parameter a string called search which is the name of the pokemon or the ID And we send that parameter to the function that makes the API call searchPokemon Note Observe the If part in the effect at the end we place an else where if the debouncedValue is empty we will not make a call to the API and we send the value of an empty object to setPokemon import useState useEffect from react import ResponseAPI from interface pokemon import searchPokemon from utils searchPokemon export const useSearchPokemon search string gt const pokemon setPokemon useState lt ResponseAPI null gt as ResponseAPI const isLoading setIsLoading useState false useEffect gt const controller new AbortController if search setIsLoading true searchPokemon search controller signal then data gt setPokemon data setIsLoading false else setPokemon as ResponseAPI return gt controller abort search return pokemon isLoading Then we call useSearchPokemon in the App tsx file import useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import useSearchPokemon from hooks useSearchPokemon import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const debouncedValue setDebouncedValue useState value const isLoading pokemon useSearchPokemon debouncedValue useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default App  Handling the logic for the Debounce effect Inside the folder src hooks we create the following file useDebounce ts and place all the logic to handle the debounce effect This custom hook receives parameters value is the value of the input status delay is the amount of time you want to delay the debounce execution and is optional Note the delay property is used as the second parameter of the setTimeout function where in case delay is undefined then the default time will be ms And also we add the delay property to the effect dependencies array import useState useEffect from react export const useDebounce value string delay number gt const debouncedValue setDebouncedValue useState value useEffect gt const timer setTimeout gt setDebouncedValue value delay return gt clearTimeout timer value delay return debouncedValue Then we call useDebounce in the App tsx file import useEffect useState from react import Input from components Input import Pokemon from components Pokemon import useInput from hooks useInput import useSearchPokemon from hooks useSearchPokemon import useDebounce from hooks useDebounce import searchPokemon from utils searchPokemon import ResponseAPI from interface pokemon const App gt const value onChange useInput const debouncedValue useDebounce value const isLoading pokemon useSearchPokemon debouncedValue return lt div className container gt lt h gt lt span gt Search Engine lt span gt whit lt span gt Debounce Effect lt span gt lt h gt lt Input value onChange gt isLoading lt span gt Loading Results lt span gt lt Pokemon pokemon pokemon gt lt div gt export default AppAnd so our App tsx component was cleaner and easier to read   Conclusion The whole process I just showed is one of the ways you can make a search engine with debounce effect I hope I helped you understand how to do this exercise thank you very much for making it this far I invite you to comment if you know any other different or better way of how to make a debounce effect for a search engine   Source code Franklin search engine debounce effect Creating a search engine with debounce effect with React JS Search Engine Debounce Effect Creating a search engine with debounce effect with React JS and Pokemon API Technologies React JSTypescriptVite JSInstalation Clone the repository git clone Run this command to install the dependencies npm install Run this command to raise the development server npm run devLinks ️Demo of the app Link to tutorial post How to make a search engine with debounde effect View on GitHub 2022-06-23 21:12:04
海外TECH DEV Community Why the web is turning away from WordPress https://dev.to/cloudcannon/why-the-web-is-turning-away-from-wordpress-1h10 Why the web is turning away from WordPressA few months ago I read a fascinating interview with Matt Mullenweg the CEO of Automattic and co founder of WordPress Among other glimpses into the inner workings of the year old company ーamong them the laudable desire to keep the internet weird ーMullenweg forecasts that of the web will be on WordPress within the next decade But which you might ask An equally important follow up question might be “How well will that of the web perform WordPress market share is slipping where it mattersOver the last year WordPress has started losing its market share among the most viewed sites on the internet This is true of the top K the top K and the top million popular websites More specifically the monolithic CMS s share of the top K sites is lower than it has been for five years ーnot just a plateau but a significant drop for a single twelve month period Yes WordPress still hovers around the mark when it comes to its share of the CMS market ーaccording to both Mullenweg and WTech s web technology surveys ーbut it s pretty clear that there s a change in the air when it comes to the sites used by the most people Sites built with static site generators by contrast are on the rise within that same five year period In fact SSGs experienced an eightfold increase in their share of the top K websites over that period If you d like to see the data yourself check out BuiltWith trends on the top K sites for WordPress Jekyll Hugo Next js Nuxt js and Gatsby Why are developers and big businesses turning away from WordPress Even though we re watching the trends it s hard to argue with raw numbers One number that s thrown around a lot is that WordPress is responsible for more that million new domain registrations per year Though that particular statistic is based on a report from it still matches current estimates Clearly WordPress is still a viable option for a great many users ーperhaps they re familiar with the interface the themes the plugins or they rely on the large install base for the inevitable troubleshooting Critical mass is after all a real phenomenon But the dominance of WordPress ーof any single platform ーcomes at a cost The larger and more monolithic a service or piece of software becomes the less flexibility it will come to have Anyone who has managed WordPress sites for longer than a few months knows how the cycle goes Upgrade PHP Upgrade and reconfigure broken plugins Find replacement plugins for those that no longer work Upgrade WordPress Upgrade PHP again And the cycle continues ad nauseam Success can be a hindrance and over almost years technical debts accrue An upgrade update cycle is true of all tech stacks to be fair but because Wordpress is server based not updating can be a severe security risk But relying on WordPress and PHP as a foundational part of your tech stack is no longer as relevant as it was and leaner less rigid and more productive frameworks have emerged in the years since WordPress was first released A typical development cycle for major product categories ーsay customer facing websites that non technical users can edit ーwould involve engineers using similar tools they use for creating their main products database webserver rendering pages on request In WordPress emerged as a standardized version of those constraints Nowadays engineers are still building them with similar tools they build their main products with it s just that those tools are different e g React Vue Svelte Static site generators like Next js Nuxt js and SvelteKit have emerged as a standardized version of those newer and less constraining constraints Because development in general is trending away from monolithic stacks we re seeing web development do the same Talented new frontend developers currently enter the workforce with neither the need or the patience to unpick almost two decades of complexity ーour current best practices include tech stacks that didn t exist just a few years ago Thus these developers work with React with Vue with Svelte ーand absent those they rely on the leanest and fastest interoperable tools in their kit pure CSS HTML and JavaScript built by SSGs like Hugo Eleventy and Jekyll Performance and security concernsWithout a lot of paring back and additional development time WordPress sites simply don t perform to our exacting modern standards To tease out the feelings behind a tweet from content marketer Brooklin Nash that s been stuck in my mind for some time our desire for instant gratification has the tendency to outpace our ability to be realistic Brooklin Nash realbrooknash Somehow I m old enough to remember dial up but young enough to rage quit any website that takes longer than seconds to load PM Feb Quite aside from slow hosts or shared servers both users and developers might experience delays on WordPress from a range of factors including out of date or non optimized plugins and themes top heavy sites with too much client side data and of course running older versions of PHP and of WordPress According to WordPress less than of WordPress sites are running the latest version of PHP and more than aren t using the latest version of WordPress itself In addition to our performance concerns we re also becoming more and more security conscious ーboth as users and developers We covered the security differences between the Jamstack approach and WordPress last year and it s fair to say that nothing s changed there ーstatic sites are simply more secure for the vast majority of users with considerably less surface area to exploit What has changed though is both the number of developers using SSGs ーand their obvious success The static site generator market is maturingOver the past few years we ve seen some high profile SSG developers move to corporate jobs in the SSG space often with some connection to their own open source SSG work ーand in most cases with the expectation that they will continue to work on these projects This isn t a surprise really ーmaking something amazing has always been the best way to find a job where you re paid to make amazing things But the fact that names such as Rich Harris Svelte SvelteKit Zach Leatherman Eleventy and Ben Holmes Slinkity are known outside of their Git repositories suggests that the value of their open source work is being explicitly recognized Corporate sponsorship of open source software is a delicate balance ーjust ask Automattic who pledge to contribute of their resources to the WordPress project ーbut it is nonetheless a strong signal that there s scope for growth in SSG software beyond GitHub sponsorships Personalities and prodigious patronage aside it s hard to argue with the numbers Even allowing for the slightly complicated arithmetic of tracking usage of multiple tools we re seeing higher numbers of developers using SSGs and even higher numbers of websites built with these modern tools The Jamstack ecosystem is expanding too Static site generators such as Hugo Eleventy and Gatsby have libraries of themes starters and plugins available to them for those developers who prefer to begin from a functional template The broad separation of SSG trends into one of four approaches ーsimplicity Eleventy Jekyll Hugo partial hydration Elder js Astro Slinkity SPAs Next js Nuxt js Gatsby Sveltekit and the full stack Redwood js Blitz js ーsuggests the category has expanded to fill every website niche currently imaginable What will the future of static sites mean for you If these trends continue ーthe downward slope of WordPress and the steady gains of SSGs among the web s most popular sites ーwe re likely to see a few changes to the web s resilience and infrastructure as well as the way we work First off we d see less reliance on and collective time spent maintaining servers and databases for sites that show the same content to all end users and a corresponding increased SEO ranking for these sites Static cached files load much faster than dynamic database queries disadvantaging those WordPress users who do not cache their sites CDNs and edge hosting companies will pick up the slack here as their services will be more in demand and sub s response times will be more likely If you re a developer a trend towards static sites means you re likely to see better dev workflows That s a nebulous claim so let me hastily qualify you ll see workflows that enable more collaboration when you need to collaborate and at the same time more independence for you and for content writers and site editors Non developers will become increasingly less reliant on devs for simple changes as static content management systems mature which we re already seeing If you re a marketer or content creator your sites will be fast by default decreasing your bounce rates and giving you better SEO ranking Any major changes will see faster turnarounds from your developers who will need to spend less of their own time fighting the framework Finally with server side analytics you ll be able to see traffic patterns with full visibility ーeven of the gt of your audience who use ad blockers that render their browsing invisible to platforms like Google Analytics If you re a web user consumer or reader ーand we all are of course ーeverything comes down to you You might not rage if a website takes more than five seconds to load but statistically you re less likely to purchase from a slow loading site to the tune of more than billion of lost sales per year On average you take approximately seconds to form your opinion of a website and if you have a good user experience on a site you re more likely to continue shopping there With that in mind an increasing number of static sites means you ll see faster site loads and will have a better more secure user experience You ll be less likely to close a tab out of exasperation and as an interesting side effect of that good UX you re more likely to stay remain a customer when you re shopping online My final point is a small one but not insignificant Because static sites are less resource intensive than database driven sites they are also more eco friendly and all else being equal a more responsible choice to make While it s a stretch to imagine that global data centre power usage would decrease in a world where static sites were the norm rather than the exception it s nonetheless reassuring that static sites enable us to choose the best of both worlds when it comes to our energy usage and site performance DX meet UX or have your cake and eat it too As static site generators have developed so have the tools that bridge the gap between developers and non technical users CloudCannon CMS for example focuses on both the developer experience DX of creating maintaining and optimizing static sites created by a growing list of SSGs as well as the user experience UX of a content editor whose working life does not need to be burdened with the knowledge or “glorious purpose if you prefer of Git and all its inner workings Bookshop one of our own open source tools allows the kind of component based editing in SSGs such as Hugo Jekyll and Eleventy that ーto put it bluntly ーno one thought was possible It s an inflection point that will affect how these SSGs will be used in the coming years think Elementor s block based builder for WordPress with increasing support for additional platforms that don t have rigid security and maintenance constraints With Bookshop developers can work with custom components on the SSG they choose without being locked into a single platform Mullenweg s aspirations to keep the internet weird are just that ーaspirational ーand seem a little at odds with the monotonous maintenance required of WordPress developers Most interpretations of weirdness sit pretty clearly in the sphere of content rather than that of structure after all and WordPress is historically inflexible when it comes to inventive site structures Little wonder then that Tumblr acquired by Automattic in carries the can for weirdness But by all means let s keep the internet weird Let s also just make sure that the sites we make perform really well by all objective measures that they re actively intuitive to build and edit and that our individual interpretations of weirdness don t depend on a tech stack that s nearly old enough to vote Yes it s true that user friendly site builders such as Squarespace and Wix are also growing at WordPress expense but they remain walled gardens with increasingly limited development options as they grow ーmore on them next week 2022-06-23 21:10:33
ニュース BBC News - Home Supreme Court ruling expands US gun rights https://www.bbc.co.uk/news/world-us-canada-61915237?at_medium=RSS&at_campaign=KARANGA court 2022-06-23 21:50:26
ニュース BBC News - Home Afghanistan earthquake: No food, no shelter and fears of cholera https://www.bbc.co.uk/news/world-asia-61918430?at_medium=RSS&at_campaign=KARANGA paktika 2022-06-23 21:34:34
ニュース BBC News - Home Super League: St Helens 42-12 Leeds Rhinos https://www.bbc.co.uk/sport/rugby-league/61881809?at_medium=RSS&at_campaign=KARANGA totally 2022-06-23 21:25:59
北海道 北海道新聞 ウクライナでマック再開か ロシア侵攻で閉鎖 https://www.hokkaido-np.co.jp/article/697418/ 開か 2022-06-24 06:43:00
北海道 北海道新聞 トランスジェンダー保護を 米政権が法改正案 https://www.hokkaido-np.co.jp/article/697417/ 法改正案 2022-06-24 06:43:00
北海道 北海道新聞 緒方が2年連続の総合V ボルダリングW杯最終戦 https://www.hokkaido-np.co.jp/article/697415/ 連続 2022-06-24 06:13:00
北海道 北海道新聞 自公、改選過半数上回る勢い 立民伸び悩み、参院選序盤情勢 https://www.hokkaido-np.co.jp/article/697414/ 共同通信社 2022-06-24 06:13:14
北海道 北海道新聞 ウクライナ「加盟候補国」に認定 EU首脳会議で合意、モルドバも https://www.hokkaido-np.co.jp/article/697411/ 欧州連合 2022-06-24 06:02:58
ビジネス 東洋経済オンライン 仕事が「1人に集中」する職場が陥る最悪の結末 仕事が振られない人にもストレスがのし掛かる | ワークスタイル | 東洋経済オンライン https://toyokeizai.net/articles/-/595989?utm_source=rss&utm_medium=http&utm_campaign=link_back 東洋経済オンライン 2022-06-24 06:40:00
ビジネス 東洋経済オンライン フジテック社長、株主総会1時間前の「敵前逃亡」 物言う株主の反対運動で、再任議案を取り下げ | 素材・機械・重電 | 東洋経済オンライン https://toyokeizai.net/articles/-/598994?utm_source=rss&utm_medium=http&utm_campaign=link_back 反対運動 2022-06-24 06:20:00
海外TECH reddit Who's your favourite islander https://www.reddit.com/r/LoveIslandTV/comments/vj7c50/whos_your_favourite_islander/ Who x s your favourite islanderView Poll submitted by u Titanium to r LoveIslandTV link comments 2022-06-23 21:14:04

コメント

このブログの人気の投稿

投稿時間:2021-06-17 22:08:45 RSSフィード2021-06-17 22:00 分まとめ(2089件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)