React: Jak używać async i await w useEffect?

Opublikowano: 07.02.2023 - tagi: React JavaScript Komponent Hook useEffect Asynchroniczność

Asynchroniczny useEffect?

Obsługa żądań HTTP w useEffect jest prosta:

import { useState, useEffect } from 'react';

const Component = () => {
	const [state, setState] = useState(null);
	
	useEffect(() => {
		fetch('/api/data').then((data) => setState(data));
	}, []);
}

A co jeśli chcesz użyć async/await?

Może tak?:

import { useState, useEffect } from 'react';

const Component = () => {
    const [state, setState] = useState(null);

    useEffect(async () => {
        const data = await fetch('/api/data');
        setState({ data });
    }, []);
}

To zadziała, ale nie powinno się pisać w taki sposób. Dlaczego? useEffect umożliwia wywołanie funkcji, kiedy komponent nie jest już potrzebny. Dzięki niej możemy po sobie posprzątać, o ile jest taka potrzeba.

Załóżmy jednak, że potrzebujesz wywołać funkcję "czyszczącą":

import { useState, useEffect } from 'react';

const Component = () => {
    const [state, setState] = useState(null);

    useEffect(async () => {
        const data = await fetch('/api/data');
        setState({ data });

        return () => {
            ...
        }
    }, []);
}

Problem polega na tym, że z powodu użycia async/await w taki sposób funkcja "czyszcząca" nigdy nie zostanie wywołana!

Jak użyć async/await?

Rozwiązanie tego problem jest bardzo proste. Można to zapisać w taki sposób:

import { useState, useEffect } from 'react';

const Component = () => {
    const [state, setState] = useState(null);

    useEffect(() => {
        const fetchData = async () => {
            const data = await fetch('/api/data');
            setState({ data });
        }
        
        fetchData();
        
        return () => {
            ...
        }
    }, []);
}

Comics: Big picture

Opublikowano: 02.02.2023 - tagi: Komiks Rysowanie Porada

Learn to look at big picture

Podsumowanie: Styczeń 2023

Opublikowano: 31.01.2023 - tagi: Podsumowanie Styczeń 2023 Blog

W styczniu opublikowałem 7 wpisów:


Inne:

  1. 6 sposobów na lepszą koncentrację

TypeScript:

  1. Jak stworzyć pustą liczbę?

React:

  1. Do czego służy useState?
  2. Do czego służy useEffect?
  3. Warunkowe renderowanie komponentów

Narysowałem dwa komiksy:

  1. Code smells
  2. Go live rule

Przeczytałem jedną książkę:

  1. Upór - Angela Duckworth

Przesłuchałem trzy audiobooki:

  1. Gra - Sara Antczak
  2. Working Hard, Hardly Working - Grace Beverly
  3. Why Has Nobody Told Me This Before - Dr Julie Smith

React: Warunkowe renderowanie komponentów

Opublikowano: 24.01.2023 - tagi: JavaScript React Komponent

W React można wyświetlać komponenty w zależności od stanu. Takie renderowanie nazywamy warunkowym.

Sposób 1: Instrukcja if

import React, { useState } from 'react';

const SalePrice = () => {
    return <h2>Price: 100$</h2>;
}

const DiscountPrice = () => {
    return <h2>Price: only 99$!!!</h2>;
}

const ProductPrice = ({isOnSale}) => {
    if (isOnSale) {
        return <DiscountPrice />
    }

    return <SalePrice />
}

const App = () => {
    const [discountPrice, setDiscountPrice] = useState(false);

    return <div>
            <ProductPrice isOnSale={discountPrice} />
            <button onClick={() => setDiscountPrice(!discountPrice)}>Toggle price</button>
        </div>;
}

Sposób 2: Operator ?:

const App = () => {
    const [discountPrice, setDiscountPrice] = useState(false);

    return <div>
            {discountPrice ? <DiscountPrice /> : <SalePrice />}
            <button onClick={() => setDiscountPrice(!discountPrice)}>Toggle price</button>
        </div>;
}

Sposób 3: Operator AND

const App = () => {
    const [error, setError] = useState(false);

    return <div>
            {error && <h2>Error!</h2>}
            <button onClick={() => setError(!error)}>Toggle error</button>
        </div>;
}

Sposób 4: Wartość null

Jeśli masz taki przypadek, że nic nie chcesz wyświetlać, wyślij po prostu wartość null:

const Error = ({message}) => {
    if (!message) {
        return null;
    }

    return <h2>{message}</h2>;
}

const App = () => {
    const [error, setError] = useState(null);

    return <div>
        <Error message={error} />
        <button onClick={() => setError('Error!')}>Set error</button>
        <button onClick={() => setError(null)}>Remove error</button>
    </div>;
}

Comics: Go live rule

Opublikowano: 19.01.2023 - tagi: Komiks Rysowanie

Go live rule