From 17d4496ad156b6649f11e7e0f44cfd5449ee362e Mon Sep 17 00:00:00 2001 From: Javier Lopez de Ancos Date: Mon, 12 Dec 2022 20:16:32 +0100 Subject: [PATCH 1/7] docs: translate api useSyncExternalStore --- .../apis/react/useSyncExternalStore.md | 135 +++++++++--------- 1 file changed, 67 insertions(+), 68 deletions(-) diff --git a/beta/src/content/apis/react/useSyncExternalStore.md b/beta/src/content/apis/react/useSyncExternalStore.md index 95afca930..25626939f 100644 --- a/beta/src/content/apis/react/useSyncExternalStore.md +++ b/beta/src/content/apis/react/useSyncExternalStore.md @@ -4,7 +4,7 @@ title: useSyncExternalStore -`useSyncExternalStore` is a React Hook that lets you subscribe to an external store. +`useSyncExternalStore` es un Hook de React que te permite suscribirte a una fuente de almacenamiento de datos externa. ```js const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot?) @@ -16,16 +16,16 @@ const snapshot = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot? --- -## Usage {/*usage*/} +## Uso {/*usage*/} -### Subscribing to an external store {/*subscribing-to-an-external-store*/} +### Subscribiéndose a una fuente de almacenamiento datos externa {/*subscribing-to-an-external-store*/} -Most of your React components will only read data from their [props,](/learn/passing-props-to-a-component) [state,](/apis/react/useState) and [context.](/apis/react/useContext) However, sometimes a component needs to read some data from some store outside of React that changes over time. This includes: +Normalmente la mayoría de tus componentes de React solo leerán datos de sus [propiedades,](/learn/passing-props-to-a-component), [estado,](/apis/react/useState) y [contexto.](/apis/react/useContext). Sin embargo, a veces un componente necesita leer algunos datos de alguna fuente de almacenamiento fuera de React que cambia con el tiempo. Esto incluye: -* Third-party state management libraries that hold state outside of React. -* Browser APIs that expose a mutable value and events to subscribe to its changes. +* Bibliotecas de gestión de estado de terceros que mantienen el estado fuera de React. +* APIs del navegador que exponen un valor mutable y eventos para suscribirse a sus cambios. -Call `useSyncExternalStore` at the top level of your component to read a value from an external data store. +Llama a `useSyncExternalStore` en el nivel mas alto de tu componente para leer un valor de una fuente de datos externa. ```js [[1, 5, "todosStore.subscribe"], [2, 5, "todosStore.getSnapshot"], [3, 5, "todos", 0]] import { useSyncExternalStore } from 'react'; @@ -37,14 +37,14 @@ function TodosApp() { } ``` -It returns the snapshot of the data in the store. You need to pass two functions as arguments: +Esto devuelve la instantánea del dato en la fuente de almacenamiento de datos. Necesitas pasar dos funciones como argumentos: -1. The `subscribe` function should subscribe to the store and return a function that unsubscribes. -2. The `getSnapshot` function should read a snapshot of the data from the store. +1. La función `subscribe` deberá suscribirse a la fuente de almacenamiento de datos y devolver una función que permita des suscribirse. +2. La función `getSnapshot` deberá obtener una instantánea del dato de la fuente de almacenamiento de datos. -React will use these functions to keep your component subscribed to the store and re-render it on changes. +React utilizará estas funciones para mantener tu componente suscrito a la fuente de almacenamiento de datos y volver a renderizarlo con los cambios. -For example, in the sandbox below, `todosStore` is implemented as an external store that stores data outside of React. The `TodosApp` component connects to that external store with the `useSyncExternalStore` Hook. +Por ejemplo, en el sandbox de a continuación, `todosStore` se implementa como una fuente de almacenamiento de datos externa que almacena datos fuera de React. El componente `TodosApp` se conecta a esta fuente de almacenamiento externa de datos con el Hook `useSyncExternalStore`. @@ -69,11 +69,11 @@ export default function TodosApp() { ``` ```js todoStore.js -// This is an example of a third-party store -// that you might need to integrate with React. +// Este es un ejemplo de una fuente de almacenamiento de datos de terceros +// que podría necesitar integrar con React. -// If your app is fully built with React, -// we recommend using React state instead. +// Si su aplicación está completamente construida con React, +// recomendamos usar el control de estado de React en su lugar. let nextId = 0; let todos = [{ id: nextId++, text: 'Todo #1' }]; @@ -106,15 +106,15 @@ function emitChange() { -When possible, we recommend to use the built-in React state with [`useState`](/apis/react/useState) and [`useReducer`](/apis/react/useReducer) instead. The `useExternalSyncStore` API is mostly useful if you need to integrate with existing non-React code. +Cuando sea posible, recomendamos usar el control de estado incorporado en React con [`useState`](/apis/react/useState) y [`useReducer`](/apis/react/useReducer) en su lugar. La `useExternalSyncStore` API is principalmente útil si necesita integrarse con código existente que no sea de React. --- -### Subscribing to a browser API {/*subscribing-to-a-browser-api*/} +### Subscribiéndose a una API de navegador {/*subscribing-to-a-browser-api*/} -Another reason to add `useSyncExternalStore` is when you want to subscribe to some value exposed by the browser that changes over time. For example, suppose that you want your component to display whether the network connection is active. The browser exposes this information via a property called [`navigator.onLine`.](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) This value can change over time without React's knowledge, so you need to read it with `useSyncExternalStore`. +Otra razón para usar `useSyncExternalStore` es cuando desea suscribirse a algún valor expuesto por el navegador que cambia con el tiempo. Por ejemplo, suponga que desea que su componente muestre si la conexión de red está activa. El navegador expone esta información a través de una propiedad llamada [`navigator.onLine`.](https://developer.mozilla.org/en-US/docs/Web/API/Navigator/onLine) Este valor puede cambiar con el tiempo sin que React sea notificado, por lo que necesitas leerlo con `useSyncExternalStore`. ```js import { useSyncExternalStore } from 'react'; @@ -124,8 +124,7 @@ function ChatIndicator() { // ... } ``` - -To implement the `getSnapshot` function, read the current value from the browser API: +Para implementar la función `getSnapshot`, lee el valor actual de la API del navegador: ```js function getSnapshot() { @@ -133,7 +132,7 @@ function getSnapshot() { } ``` -Next, you need to implement the `subscribe` function. For example, when `navigator.onLine` changes, the browser fires the [`online`](https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event) and [`offline`](https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event) events on the `window` object. You need to subscribe the `callback` argument to the corresponding events, and then return a function that cleans up the subscriptions: +A continuación, debes implementar la función `subscribe`. Por ejemplo, cuando `navigator.onLine` cambia, el navegador activa los eventos [`online`](https://developer.mozilla.org/en-US/docs/Web/API/Window/online_event) y [`offline` ](https://developer.mozilla.org/en-US/docs/Web/API/Window/offline_event) en el objeto `window`. Debe suscribir el argumento `callback` a los eventos correspondientes y luego devolver una función que limpie estas suscripciones: ```js function subscribe(callback) { @@ -146,7 +145,7 @@ function subscribe(callback) { } ``` -Now React knows how to read the value from the external `navigator.onLine` API and how to subscribe to its changes. Try to disconnect your device from the network and notice that the component re-renders in response: +Ahora React sabe cómo leer el valor de la API `navigator.onLine` externa y cómo suscribirse a sus cambios. Intente desconectar su dispositivo de la red y observe que el componente se vuelve a renderizar en respuesta: @@ -176,11 +175,11 @@ function subscribe(callback) { --- -### Extracting the logic to a custom Hook {/*extracting-the-logic-to-a-custom-hook*/} +### Extrayendo la lógica en un Hook personalizado {/*extracting-the-logic-to-a-custom-hook*/} -Usually you won't write `useSyncExternalStore` directly in your components. Instead, you'll typically call it from your own custom Hook. This lets you use the same external store from different components. +Por lo general, no deberías escribir `useSyncExternalStore` directamente en tus componentes. En su lugar, normalmente lo llamarás desde tu propio Hook personalizado. Esto te permite usar la misma fuente de almacenamiento externa desde diferentes componentes. -For example, this custom `useOnlineStatus` Hook tracks whether the network is online: +Por ejemplo, este Hook personalizado `useOnlineStatus` monitoriza si la red está en línea: ```js {3,6} import { useSyncExternalStore } from 'react'; @@ -199,7 +198,7 @@ function subscribe(callback) { } ``` -Now different components can call `useOnlineStatus` without repeating the underlying implementation: +Ahora diferentes componentes pueden llamar a `useOnlineStatus` sin repetir la implementación subyacente: @@ -261,14 +260,14 @@ function subscribe(callback) { --- -### Adding support for server rendering {/*adding-support-for-server-rendering*/} +### Añadiendo soporte para la renderización en el servidor {/*adding-support-for-server-rendering*/} -If your React app uses [server rendering,](/apis/react-dom/server) your React components will also run outside the browser environment to generate the initial HTML. This creates a few challenges when connecting to an external store: +Si su aplicación React usa [renderización en el servidor,](/apis/react-dom/server), sus componentes React también se ejecutarán fuera del entorno del navegador para generar el HTML inicial. Esto crea algunos desafíos cuando se conecta a una fuente de datos externa: -- If you're connecting to a browser-only API, it won't work because it does not exist on the server. -- If you're connecting to a third-party data store, you'll need its data to match between the server and client. +- Si se está conectando a una API unicamente de navegador, no funcionará porque no existe en el servidor. +- Si se está conectando a una fuente de datos externa de terceros, necesitará que sus datos coincidan entre el servidor y el cliente. -To solve these issues, pass a `getServerSnapshot` function as the third argument to `useSyncExternalStore`: +Para resolver estos problemas, pase una función `getServerSnapshot` como tercer argumento a `useSyncExternalStore`: ```js {4,12-14} import { useSyncExternalStore } from 'react'; @@ -291,26 +290,26 @@ function subscribe(callback) { } ``` -The `getServerSnapshot` function is similar to `getSnapshot`, but it runs only in two situations: +La función `getServerSnapshot` es similar a `getSnapshot`, pero solo se ejecuta en dos situaciones: -- It runs on the server when generating the HTML. -- It runs on the client during [hydration](/apis/react-dom/client/hydrateRoot), i.e. when React takes the server HTML and makes it interactive. +- Se ejecuta en el servidor al generar el HTML. +- Se ejecuta en el cliente durante la [hidratación](/apis/react-dom/client/hydrateRoot), es decir, cuando React toma el HTML del servidor y lo hace interactivo. -This lets you provide the initial snapshot value which will be used before the app becomes interactive. If there is no meaningful initial value for the server rendering, you can [force the component to render only on the client.](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content) +Esto le permite proporcionar la instantánea del valor inicial que se utilizará antes de que la aplicación se vuelva interactiva. Si no hay un valor inicial significativo para la representación del servidor, puede [forzar el componente para que se renderize solo en el cliente.](/apis/react/Suspense#providing-a-fallback-for-server-errors-and-server-only-content) -Make sure that `getServerSnapshot` returns the same exact data on the initial client render as it returned on the server. For example, if `getServerSnapshot` returned some prepopulated store content on the server, you need to transfer this content to the client. One common way to do this is to emit a `