Wednesday, April 17, 2019

React Native Component State to Hooks for a Fetch Request

Component State to Hooks for a Fetch Request (React Native)

import React, { Component, useEffect, useState } from 'react'
import { View, Text, SafeAreaView, FlatList, ActivityIndicator, Button } from 'react-native'

const Home = () => {
    const [loading, setLoading] = useState(true)
    const [people, setPeople] = useState([])
    const [page, setPage] = useState(1)

    
    useEffect(()=>{
        setLoading(true);
        fetch(`https://swapi.co/api/people?page=${page}`)
        .then(res=>res.json())
        .then(res=>{
            setPeople([...people, ...res.results]);
            setLoading(false)
        })
    },[page])

    return(
        <SafeAreaView style={{flex:1}}>
        <FlatList
        data={people}
        keyExtractor={(item)=>item.url}
        renderItem={({item, index})=>(
            <View key={index}>
                <Text style={{fontSize:20, color:'blue', fontWeight:'bold'}}>{item.name}</Text>
            </View>
        )}
        ListFooterComponent={loading ? <ActivityIndicator/>:(
            <Button title='Load more' onPress={()=>{setPage(page+1)}}>

            </Button>
        )}
        />
        
        </SafeAreaView>
        

        
    )
}



    



export default class App extends Component {
    render() {
        return (
            <Home />
        )
    }

}






display







CLEAN CODE.................................................................................................................................................................................const useSwapiPeople = () => {
  const [people, setPeople] = useState([]);
  const [loading, setLoading] = useState(false);
  const [page, setPage] = useState(1);

  useEffect(
    () => {
      setLoading(true);
      fetch(`https://swapi.co/api/people?page=${page}`)
        .then(res => res.json())
        .then(res => {
          setPeople([...people, ...res.results]);
          setLoading(false);
        });
    },
    [page]
  );

  const loadMore = () => {
    setPage(page + 1);
  };

  return {
    people,
    loading,
    loadMore,
  };
};

export default () => {
  const { people, loading, loadMore } = useSwapiPeople();

  return (
    <SafeAreaView style={{ flex: 1 }}>
      <FlatList
        data={people}
        keyExtractor={item => item.url}
        renderItem={({ item }) => (
          <View>
            <Text>{item.name}</Text>
          </View>
        )}
        ListFooterComponent={
          loading ? (
            <ActivityIndicator />
          ) : (
            <Button title="Load More" onPress={loadMore} />
          )
        }
      />
    </SafeAreaView>
  );
};





ANOTHER EXAMPLE................................................................................................................................................................................................................


import React, {useState, useEffect} from 'react';
import Api from "../api";
function UsersWithHooks() {
   const [data, setData] = useState([]);
   const [loading, setLoading] = useState(true);
   const [error, setError] = useState('');
   useEffect(async () => {
       try {
           const response = await Api.getUsers();
           const json = await response.json();
           setData(json);
       } catch (e) {
           setError(e.message || 'Unexpected error');
       }
       setLoading(false);
   }, []);
   if (loading) {
       return <div>Loading</div>
   }
   if (error) {
       return <div style={{color: 'red'}}>ERROR: {error}</div>
   }
   return (
       <table>
           <thead>
           <tr>
               <th>First Name</th>
               <th>Last Name</th>
               <th>Active?</th>
               <th>Posts</th>
               <th>Messages</th>
           </tr>
           </thead>
           <tbody>
           {data.map(u =>
               <tr key={u.id}>
                   <td>{u.firstName}</td>
                   <td>{u.lastName}</td>
                   <td>{u.active ? 'Yes' : 'No'}</td>
                   <td>{u.posts}</td>
                   <td>{u.messages}</td>
               </tr>
           )}
           </tbody>
       </table>
   );
}
export default UsersWithHooks;

......................................................................................................................................................................................................................
Example 4

Fetching Data from an API with React Hooks useEffect

import React, { useEffect, useState } from 'react'

export default () => {
  const [people, setPeople] = useState()
  useEffect(async () => {
    const response = await fetch('https://randomuser.me/api/')
    const data = await response.json()
    const [item] = data.results
    setPeople(item)

  }, [])
  return (
    <div>
      {people && <div>
        <h1>{people.gender}</h1>
        <h1>{people.name.first}</h1>
        <img src={people.picture.thumbnail} />
      </div>}
    </div>

  )
}

Eaxample 5
.......................................................................................................................................................................................................................................

import React, { Component, useState, useEffect } from 'react';
const Home = () => {
  const [error, setError]=useState(false)
  const [Data, setData] = useState({})

  const fetchData=async()=>{
    const res = await fetch('https://swapi.co/api/planets/4/')
    .then(res=>res.json())
    .then(res => setData(res))
    .catch(err=>setError(err))
  }

useEffect(()=>{
  fetchData()
},[])

  return (
    <div>
      <span>
        {JSON.stringify(Data)}
      </span>
    </div>
  )
}

class App extends Component {
  
  render() {
    return (
      <Home />
    );
  }
}

export default App;



1 comment: