Skip to content

Commit 5ffda45

Browse files
authored
Tradução das seções restantes de useOptimistic.md para Português (Brasil) (#1297)
* Tradução das seções restantes de `useOptimistic.md` para Português (Brasil) * Mantém "state" em inglês nos comentários de código
1 parent 05d1dd4 commit 5ffda45

1 file changed

Lines changed: 35 additions & 35 deletions

File tree

‎src/content/reference/react/useOptimistic.md‎

Lines changed: 35 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -337,45 +337,45 @@ export async function submitForm() {
337337
338338
</Sandpack>
339339
340-
When the button is clicked, `setIsPending(true)` uses optimistic state to immediately show "Submitting..." and disable the button. When the Action is done, `isPending` is rendered as `false` automatically.
340+
Quando o botão é clicado, `setIsPending(true)` usa o estado otimista para mostrar imediatamente "Submitting..." e desabilitar o botão. Quando a Ação termina, `isPending` é renderizado como `false` automaticamente.
341341
342-
This pattern automatically shows a pending state however `action` prop is used with `Button`:
342+
Esse padrão mostra automaticamente um estado pendente, não importa como a prop `action` seja usada com `Button`:
343343
344344
```js
345-
// Show pending state for a state update
345+
// Mostra o state pendente para uma atualização de state
346346
<Button action={() => { setState(c => c + 1) }} />
347347

348-
// Show pending state for a navigation
348+
// Mostra o state pendente para uma navegação
349349
<Button action={() => { navigate('/done') }} />
350350

351-
// Show pending state for a POST
351+
// Mostra o state pendente para um POST
352352
<Button action={async () => { await fetch(/* ... */) }} />
353353

354-
// Show pending state for any combination
354+
// Mostra o state pendente para qualquer combinação
355355
<Button action={async () => {
356356
setState(c => c + 1);
357357
await fetch(/* ... */);
358358
navigate('/done');
359359
}} />
360360
```
361361
362-
The pending state will be shown until everything in the `action` prop is finished.
362+
O estado pendente vai ser exibido até que tudo na prop `action` termine.
363363
364364
<Note>
365365
366-
You can also use [`useTransition`](/reference/react/useTransition) to get pending state via `isPending`.
366+
Você também pode usar [`useTransition`](/reference/react/useTransition) para obter o estado pendente via `isPending`.
367367
368-
The difference is that `useTransition` gives you the `startTransition` function, while `useOptimistic` works with any Transition. Use whichever fits your component's needs.
368+
A diferença é que `useTransition` fornece a função `startTransition`, enquanto `useOptimistic` funciona com qualquer Transição. Use o que fizer mais sentido para o seu componente.
369369
370370
</Note>
371371
372372
---
373373
374-
### Updating props or state optimistically {/*updating-props-or-state-optimistically*/}
374+
### Atualizando props ou estado de forma otimista {/*updating-props-or-state-optimistically*/}
375375
376-
You can wrap props or state in `useOptimistic` to update it immediately while an Action is in progress.
376+
Você pode envolver props ou estado em `useOptimistic` para atualizá-los imediatamente enquanto uma Ação está em andamento.
377377
378-
In this example, `LikeButton` receives `isLiked` as a prop and immediately toggles it when clicked:
378+
Neste exemplo, `LikeButton` recebe `isLiked` como prop e o alterna imediatamente quando clicado:
379379
380380
<Sandpack>
381381
@@ -420,7 +420,7 @@ export default function App() {
420420
```js src/actions.js hidden
421421
export async function toggleLike(value) {
422422
return await new Promise((res) => setTimeout(() => res(value), 1000));
423-
// In a real app, this would update the server
423+
// Em um app real, isto atualizaria o servidor
424424
}
425425
```
426426
@@ -432,29 +432,29 @@ import './styles.css';
432432
import App from './App';
433433

434434
const root = createRoot(document.getElementById('root'));
435-
// Not using StrictMode so double render logs are not shown.
435+
// Sem StrictMode, para que os logs da renderização dupla não apareçam.
436436
root.render(<App />);
437437
```
438438
439439
</Sandpack>
440440
441-
When the button is clicked, `setOptimisticIsLiked` immediately updates the displayed state to show the heart as liked. Meanwhile, `await toggleLike` runs in the background. When the `await` completes, `setIsLiked` parent updates the "real" `isLiked` state, and the optimistic state is rendered to match this new value.
441+
Quando o botão é clicado, `setOptimisticIsLiked` atualiza imediatamente o estado exibido para mostrar o coração como curtido. Enquanto isso, `await toggleLike` é executado em segundo plano. Quando o `await` termina, o `setIsLiked` do componente pai atualiza o estado `isLiked` "real", e o estado otimista é renderizado de acordo com esse novo valor.
442442
443443
<Note>
444444
445-
This example reads from `optimisticIsLiked` to calculate the next value. This works when the base state won't change, but if the base state might change while your Action is pending, you may want to use a state updater or the reducer.
445+
Este exemplo lê `optimisticIsLiked` para calcular o próximo valor. Isso funciona quando o estado base não vai mudar, mas, se o estado base puder mudar enquanto a sua Ação está pendente, talvez seja melhor usar uma função atualizadora ou o reducer.
446446
447-
See [Updating state based on the current state](#updating-state-based-on-current-state) for an example.
447+
Veja [Atualizando o estado com base no estado atual](#updating-state-based-on-current-state) para um exemplo.
448448
449449
</Note>
450450
451451
---
452452
453-
### Updating multiple values together {/*updating-multiple-values-together*/}
453+
### Atualizando vários valores juntos {/*updating-multiple-values-together*/}
454454
455-
When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent.
455+
Quando uma atualização otimista afeta vários valores relacionados, use um reducer para atualizá-los juntos. Isso garante que a UI permaneça consistente.
456456
457-
Here's a follow button that updates both the follow state and follower count:
457+
Aqui está um botão de seguir que atualiza tanto o estado de seguir quanto a contagem de seguidores:
458458
459459
<Sandpack>
460460
@@ -533,48 +533,48 @@ export async function unfollowUser(name) {
533533
534534
</Sandpack>
535535
536-
The reducer receives the new `isFollowing` value and calculates both the new follow state and the updated follower count in a single update. This ensures the button text and count always stay in sync.
536+
O reducer recebe o novo valor de `isFollowing` e calcula tanto o novo estado de seguir quanto a contagem de seguidores atualizada em uma única atualização. Isso garante que o texto do botão e a contagem fiquem sempre sincronizados.
537537
538538
539539
<DeepDive>
540540
541-
#### Choosing between updaters and reducers {/*choosing-between-updaters-and-reducers*/}
541+
#### Escolhendo entre funções atualizadoras e reducers {/*choosing-between-updaters-and-reducers*/}
542542
543-
`useOptimistic` supports two patterns for calculating state based on current state:
543+
`useOptimistic` suporta dois padrões para calcular o estado com base no estado atual:
544544
545-
**Updater functions** work like [useState updaters](/reference/react/useState#updating-state-based-on-the-previous-state). Pass a function to the setter:
545+
**Funções atualizadoras** funcionam como as [funções atualizadoras do useState](/reference/react/useState#updating-state-based-on-the-previous-state). Passe uma função para o setter:
546546
547547
```js
548548
const [optimistic, setOptimistic] = useOptimistic(value);
549549
setOptimistic(current => !current);
550550
```
551551
552-
**Reducers** separate the update logic from the setter call:
552+
**Reducers** separam a lógica de atualização da chamada do setter:
553553
554554
```js
555555
const [optimistic, dispatch] = useOptimistic(value, (current, action) => {
556-
// Calculate next state based on current and action
556+
// Calcula o próximo state com base no state atual e na action
557557
});
558558
dispatch(action);
559559
```
560560
561-
**Use updaters** for calculations where the setter call naturally describes the update. This is similar to using `setState(prev => ...)` with `useState`.
561+
**Use funções atualizadoras** para cálculos em que a chamada do setter descreve naturalmente a atualização. É parecido com usar `setState(prev => ...)` com `useState`.
562562
563-
**Use reducers** when you need to pass data to the update (like which item to add) or when handling multiple types of updates with a single hook.
563+
**Use reducers** quando precisar passar dados para a atualização (como qual item adicionar) ou quando tratar vários tipos de atualização com um único Hook.
564564
565-
**Why use a reducer?**
565+
**Por que usar um reducer?**
566566
567-
Reducers are essential when the base state might change while your Transition is pending. If `todos` changes while your add is pending (for example, another user added a todo), React will re-run your reducer with the new `todos` to recalculate what to show. This ensures your new todo is added to the latest list, not an outdated copy.
567+
Reducers são essenciais quando o estado base pode mudar enquanto a sua Transição está pendente. Se `todos` mudar enquanto a sua adição está pendente (por exemplo, outro usuário adicionou um todo), o React vai executar o seu reducer de novo com o novo `todos` para recalcular o que mostrar. Isso garante que o seu novo todo seja adicionado à lista mais recente, e não a uma cópia desatualizada.
568568
569-
An updater function like `setOptimistic(prev => [...prev, newItem])` would only see the state from when the Transition started, missing any updates that happened during the async work.
569+
Uma função atualizadora como `setOptimistic(prev => [...prev, newItem])` só veria o estado do momento em que a Transição começou, perdendo quaisquer atualizações que tenham acontecido durante o trabalho assíncrono.
570570
571571
</DeepDive>
572572
573573
---
574574
575-
### Optimistically adding to a list {/*optimistically-adding-to-a-list*/}
575+
### Adicionando itens a uma lista de forma otimista {/*optimistically-adding-to-a-list*/}
576576
577-
When you need to optimistically add items to a list, use a `reducer`:
577+
Quando você precisar adicionar itens a uma lista de forma otimista, use um `reducer`:
578578
579579
<Sandpack>
580580
@@ -637,7 +637,7 @@ export default function TodoList({ todos, addTodoAction }) {
637637
```js src/actions.js hidden
638638
export async function addTodo(todo) {
639639
await new Promise((res) => setTimeout(res, 1000));
640-
// In a real app, this would save to the server
640+
// Em um app real, isto salvaria no servidor
641641
return { ...todo, pending: false };
642642
}
643643
```
@@ -921,7 +921,7 @@ export default function ItemList({ items, deleteAction }) {
921921
```js src/actions.js hidden
922922
export async function deleteItem(id) {
923923
await new Promise((res) => setTimeout(res, 1000));
924-
// Item 3 always fails to demonstrate error recovery
924+
// O item 3 sempre falha, para demonstrar a recuperação de erros
925925
if (id === 3) {
926926
throw new Error('Cannot delete. Permission denied.');
927927
}

0 commit comments

Comments
 (0)