React Native
API entegrasyonu
fetch ile API entegrasyonu yazarsın.
API'den görevleri yükle
Bu derste tasks state'ini API'den gelen veriyle dolduracağız. useEffect içinde fetch çağırır, dönen JSON'u setTasks ile state'e yazarız. Bu, gerçek bir uygulamanın veri akışını taklit eder.
API URL'i 'https://api.example.com/tasks' olsun. useEffect'in bağımlılık dizisi [] olur; böylece yalnızca mount'ta bir kez çalışır. fetch bir promise döndürür; .then((res) => res.json()) ile JSON'a çevirir, .then((data) => setTasks(data)) ile state'e yazarız. Bu akış, React Native uygulamalarında veri yükleme standardıdır.
useEffect ile yükle
useEffect, bileşen mount olduğunda çalışan bir hook'tur. Bağımlılık dizisi [] verirsen yalnızca bir kez çalışır. İçinde fetch çağırıp veriyi yüklersin.
Örnek: useEffect(() => { fetch(url).then((res) => res.json()).then((data) => setTasks(data)); }, []). Burada fetch bir promise döndürür; .then zinciri ile önce JSON'a çevirir, sonra state'e yazarız. Bağımlılık dizisi boş olduğu için bu akış yalnızca mount'ta çalışır; tekrar tetiklenmez. Hata yönetimi için .catch eklenebilir; ama bu derste temel akışa odaklanıyoruz.
Uygulama useEffect ile fetch ekle
Mevcut App bileşenine useEffect ekle. Bağımlılık dizisi [] olsun. İçinde fetch('https://api.example.com/tasks') çağır; .then((res) => res.json()) ile JSON'a çevir; .then((data) => setTasks(data)) ile state'e yaz.
Örnek çözümü göster
import React, { useState, useEffect, createContext, useContext } from "react";
import { Text } from "react-native";
const TasksContext = createContext();
export function useTasks() {
return useContext(TasksContext);
}
function App() {
const [tasks, setTasks] = useState([]);
useEffect(() => {
fetch("https://api.example.com/tasks")
.then((res) => res.json())
.then((data) => setTasks(data));
}, []);
return (
<TasksContext.Provider value={{ tasks, setTasks }}>
<Text>Görevler</Text>
</TasksContext.Provider>
);
}
Kendini test et
-
Akışı rolüne eşle
- useEffect
- Mount'ta çalışır
- fetch
- API isteği atar
- .json()
- JSON'a çevirir
- setTasks
- State yazar
-
fetch çağrısı
const data = await ____(url);
Cevabı göster
const data = await fetch(url);
-
API'den gelen veri hangi formattadır?
fetch(url).then((res) => res.json());
Cevabı göster
JSON — API'den gelen veri JSON formatındadır.
Sıradaki ders: Navigation