Używamy cookies, żeby zwiększyć Twoje doświadczenia na stronie
CodeWorlds

API Integration - External Services

Integracja z zewnętrznymi API (Weather, Maps, Payment).

Weather API 🌤️

1async function getWeather(city: string) {
2  const res = await fetch(
3    `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=YOUR_KEY`
4  );
5  return res.json();
6}
7
8function WeatherWidget() {
9  const [weather, setWeather] = useState(null);
10  const [city, setCity] = useState("Warsaw");
11
12  useEffect(() => {
13    getWeather(city).then(setWeather);
14  }, [city]);
15
16  if (!weather) return <div>Loading...</div>;
17
18  return (
19    <div className="border rounded p-4">
20      <h3 className="font-bold">{weather.name}</h3>
21      <p className="text-4xl">{Math.round(weather.main.temp - 273.15)}°C</p>
22      <p>{weather.weather[0].description}</p>
23    </div>
24  );
25}

Payment Integration - Stripe 💳

1npm install @stripe/stripe-js @stripe/react-stripe-js
1import { loadStripe } from '@stripe/stripe-js';
2import { Elements, CardElement, useStripe, useElements } from '@stripe/react-stripe-js';
3
4const stripePromise = loadStripe('pk_test_...');
5
6function CheckoutForm() {
7  const stripe = useStripe();
8  const elements = useElements();
9
10  const handleSubmit = async (e: React.FormEvent) => {
11    e.preventDefault();
12    if (!stripe || !elements) return;
13
14    const cardElement = elements.getElement(CardElement);
15    const { error, paymentMethod } = await stripe.createPaymentMethod({
16      type: 'card',
17      card: cardElement!
18    });
19
20    if (!error) {
21      console.log('Payment Method:', paymentMethod);
22    }
23  };
24
25  return (
26    <form onSubmit={handleSubmit}>
27      <CardElement />
28      <button type="submit" disabled={!stripe}>
29        Pay
30      </button>
31    </form>
32  );
33}
34
35function Payment() {
36  return (
37    <Elements stripe={stripePromise}>
38      <CheckoutForm />
39    </Elements>
40  );
41}

Do zobaczenia! 🚀

Przejdź do CodeWorlds