Felhasználói eszközök

Eszközök a webhelyen


oktatas:telefon:react_native:adat_http_szerverrol

< React Native

Adat HTTP szerverről

Online adatok

REST API mókolás

cars.json
{
    "cars": [
        {
            "id": 1,
            "plate": "ADG-284",
            "color": "fehér",
            "brand": "Opel",
            "year": 1998,
            "capacity": 1400,
            "fuel": "benzin",
            "price": 260000,
            "sold": true
        },
        {
            "id": 2,
            "plate": "GAD-912",
            "color": "piros",
            "brand": "Ford",
            "year": 2003,
            "capacity": 1400,
            "fuel": "benzin",
            "price": 370000,
            "sold": true
        },
        {
            "id": 3,
            "plate": "FDE-102",
            "color": "fehér",
            "brand": "Ford",
            "year": 2004,
            "capacity": 1200,
            "fuel": "benzin",
            "price": 299000,
            "sold": false
        },
        {
            "id": 4,
            "plate": "FLE-582",
            "color": "fekete",
            "brand": "Honda",
            "year": 2003,
            "capacity": 1400,
            "fuel": "benzin",
            "price": 579000,
            "sold": false
        },
        {
            "id": 5,
            "plate": "FDN-132",
            "color": "kék",
            "brand": "Citroen",
            "year": 2006,
            "capacity": 1600,
            "fuel": "dízel",
            "price": 478000,
            "sold": false
        }
    ]
}

json-server indítása:

json-server --host 0.0.0.0 --port 8000 ./cars.json --watch

A telefon számára szükséges a --host kapcsoló használata.

Vagy:

Lekérés

App.js
import { StatusBar } from 'expo-status-bar';
import React from 'react';
import { 
  StyleSheet, 
  Text, 
  View, 
  FlatList, 
  Button
} from 'react-native';
import { useState, useEffect } from 'react';
 
 
export default function App() {
 
  const url1 = 'http://192.168.5.5:8000/cars';
  const url2 = '';
 
  const [cars, setCars] = useState([]);
 
  function handleFetchButton() {
    fetch(url1)
    .then(resp => resp.json())
    .then(data => {            
      setCars(data);      
    })
    .catch( error => {
      alert('Hiba: ' + error);
    })
  }
 
  return (
    <View style={styles.container}>
    <Text>Járművek</Text>
    <Button 
      title="Lekér"
      onPress={handleFetchButton}
    />
 
      <FlatList 
        data = {cars}
        renderItem={ ({item}) => (
          <Text>{item.plate}</Text>
        )}
      />
      <StatusBar style="auto" />
    </View>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

Ha a fetch utasítást nem tesszük függvénybe, akkor a végtelenségig fut, mivel folyamatosan renderelve van a telefon felülete.

Másik példa

{
    "title": "Barátok",
    "desc": "A barátok adatai",
    "friends" : [
        {"id": "1", "name" : "Peres Béla", "age": "37", "hobby": "alvás"},
        {"id": "2", "name" : "Teke Barna", "age": "34", "hobby": "ivás"},
        {"id": "3", "name" : "Apró Lenke", "age": "27", "hobby": "evés"}
    ]
}
App.js
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, ActivityIndicator } from 'react-native';
 
 
const dataURL = "https://gist.githubusercontent.com/andteki/91c74e1ae7f292ec02f100e09fe52c7f/raw/487f4dd6e0e9da0bab6e8920b1c3b9f2c6b70e8f/test.json"
 
export default function App() {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [title, setTitle] = useState([]);
  const [desc, setDesc] = useState([]);
 
  useEffect(() => {
    fetch(dataURL)
    .then((response) => response.json())
    .then((data) => {
      setData(data.friends);
      setTitle(data.title);
      setDesc(data.desc);
    })
    .catch((error) => alert(error))
    .finally(()=>setLoading(false));
  });
 
  return (
    <View style={styles.container}>
      {isLoading ? (
        <ActivityIndicator />
      ) : (
        <View>          
          <Text style={styles.title}>{title}</Text>
          <FlatList
            data = {data}
            keyExtractor={({ id }, index) => id}
            renderItem={({item}) => (
              <Text style={styles.friend} >
                {item.name} - {item.age}
              </Text>
            )}
          />
          <Text style={styles.desc}>{desc}</Text>
        </View>
 
      )}
    </View>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 25,
  },
  friend: {
    fontSize: 22,    
  },
  title: {
    fontSize: 30,
    fontWeight: "bold",
  },
  desc: {
    textAlign: "center",
    marginBottom: 100,
    color: "#333",
  }
});

A <ActivityIndicator /> komponens megjelenít és animációt, ami jelzi, hogy még töltődik a JSON. Gyors letöltés esetén ez nem jelenik meg.

HTTP státuszkód

let url = 'https://zold.lan'
fetch(url)
.then(res => {      
  console.log(res.status)
})
.catch( error => {
  console.log('Hiba')
})

ActivityIndicator-ral

App.js
import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, FlatList, ActivityIndicator } from 'react-native';
 
 
const dataURL = "https://gist.githubusercontent.com/andteki/91c74e1ae7f292ec02f100e09fe52c7f/raw/487f4dd6e0e9da0bab6e8920b1c3b9f2c6b70e8f/test.json"
 
export default function App() {
  const [isLoading, setLoading] = useState(true);
  const [data, setData] = useState([]);
  const [title, setTitle] = useState([]);
  const [desc, setDesc] = useState([]);
 
  useEffect(() => {
    fetch(dataURL)
    .then((response) => response.json())
    .then((json) => {
      setData(json.friends);
      setTitle(json.title);
      setDesc(json.desc);
    })
    .catch((error) => alert(error))
    .finally(setLoading(false));
  });
 
  return (
    <View style={styles.container}>
      {isLoading ? (
        <ActivityIndicator />
      ) : (
        <View>          
          <Text style={styles.title}>{title}</Text>
          <FlatList
            data = {data}
            keyExtractor={({ id }, index) => id}
            renderItem={({item}) => (
              <Text style={styles.friend} >
                {item.name} - {item.age}
              </Text>
            )}
          />
          <Text style={styles.desc}>{desc}</Text>
        </View>
 
      )}
    </View>
  );
}
 
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
    marginTop: 25,
  },
  friend: {
    fontSize: 22,    
  },
  title: {
    fontSize: 30,
    fontWeight: "bold",
  },
  desc: {
    textAlign: "center",
    marginBottom: 100,
    color: "#333",
  }
});

Linkek

oktatas/telefon/react_native/adat_http_szerverrol.txt · Utolsó módosítás: 2022/01/01 13:08 szerkesztette: admin