Url exacta usada: https://api.coinlore.net/api/tickers/
Introducción a React Native
Qué aprenderás sobre React Native y el proyecto que harás
Instalación React Native CLI en Windows
Instalación React Native CLI en MacOS
Estructura de un proyecto en react native
Configuración de la navegación en react native
Nuestra primera pantalla con Stack Navigator
Iniciando el desarrollo de nuestra aplicación
Navegación entre pantallas
Usando una REST API con fetch
Crear nuestra primera lista con FlatList
Dando estilos a nuestra FlatList
Pasar información entre pantallas
Creando nuestra vista detalle
Creando una FlatList horizontal
Elementos avanzados
Buscador con TextInput
Agregando tabs de navegación
Creando nuestra sección de favoritos
Creando nuestra librerÃa de storage
Agregando favoritos
Eliminando favoritos
Lista de favoritos
Cierre
MentorÃa Expert
Modelos mentales y buenas prácticas con React.js
No tienes acceso a esta clase
¡Continúa aprendiendo! Únete y comienza a potenciar tu carrera
Aportes 21
Preguntas 6
Url exacta usada: https://api.coinlore.net/api/tickers/
Un ejemplo de la clase usando Hooks
const CoinsScreen = (props) => {
const [data, setdata] = useState({});
const getData = async () => {
let res = await gethttps('tickers');
setdata(res);
console.log(res);
};
useEffect(() => {
getData();
}, []);
function handlePress() {
console.log('go to:', props);
props.navigation.navigate('CoinDetail');
}
return (
<>
<View style={style.container}>
<Text style={style.title}> Coins Screen</Text>
<Pressable style={style.btn} onPress={() => handlePress()}>
<Text style={style.btnText}>BOTON</Text>
</Pressable>
</View>
</>
);
};
export default CoinsScreen;```
Aquà la tarea 😃, cambie el nombre del método delete por remove para evitar usar palabras reservadas del lenguaje.
class Http {
static instance = new Http();
get = async (url) => {
try {
const request = await fetch(url);
const json = await request.json();
return json;
} catch (err) {
console.error('HTTP GET Error: ', err);
throw Error(err);
}
};
post = async (url, body) => {
try {
const requet = await fetch(url, {
method: 'POST',
body,
});
const json = await requet.json();
return json;
} catch (err) {
console.error('HTTP POST Error: ', err);
throw Error(err);
}
};
remove = async (url) => {
try {
const request = await fetch(url, {
method: 'DELETE',
});
const json = await request.json();
return json;
} catch (err) {
console.error('HTTP DELETE Error: ', err);
throw Error(err);
}
};
put = async (url, body) => {
try {
const request = await fetch(url, {
method: 'PUT',
body,
});
const json = await request.json();
return json;
} catch (err) {
console.error('HTTP PUT Error: ', err);
throw Error(err);
}
};
}
export default Http;
Hola Devs:
-Aca les muestro como lo implemente haciendo uso de los hooks , el useEffect :
Repositorio: Crypto-Tracker
Recuerda, #NuncaParesDeAprender 💚
Les dejo una función que pueden utilizar en vez de crear una para cada método Http, utilizando igualmente un wrapper asà que se puede reemplazar Axios por fetch o cualquier otro.
HttpRequest = async ({url, method, body, options, headers}) => {
body = typeof body === 'string' ? body : JSON.stringify(body);
try {
const {data} = await axios(url, {
method,
body,
headers: {
'Content-Type': 'application/json',
...headers,
},
...options,
});
return data;
} catch (error) {
console.error(error);
return null;
}
};
FLUJO DE TRABAJO REACT NATIVE
APP.JS
app.js se encarga de cargar las dependencias necesarias, complementos y componentes que se crean como si fueran las ventanas, este archivo será la carga inicial de todos, se encarga de cargar en el entorno de navegación de ReactNavgation: Navigation container y el contenedor de los stacks
SRC
• COMPONENTS
o CoinStack.js
Coinstack hace referencia a la dependencia que será contenedor de stacks como si fueran paginas para navegar dentro del proyecto que a su vez son componentes
o CoinDetailScreen.js
o CoinScreen.js
Estos son los componentes que derivan de component y a su vez serán cargados luego en el STACK contenedor para que el navigation container lo represente
RESUMEN
• NavigationContainer
o Stack
ï‚§ React Navigation Stack
ï‚§ Navigator stack
ï‚§ Stack screen
• components
o components
ï‚§ styles
ï‚§ component basic
Este es el hook que estoy usando, yo uso Typescript, pero si quitan los tipos se puede usar en Javascript.
import { useState, useEffect } from "react";
type Options = {
method?: string;
body?: unknown;
};
const useFetch = (url: string, options: Options) => {
const [response, setResponse] = useState<null | Response>(null);
const [error, setError] = useState<null | unknown>(null);
const [isLoading, setIsLoading] = useState<boolean>(false);
useEffect(() => {
const fetchData = async () => {
setIsLoading(true);
try {
const res = await fetch(url, options);
const json = await res.json();
setResponse(json);
setIsLoading(false);
} catch (e) {
setError(e);
}
};
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return { response, error, isLoading };
};
export default useFetch;
import { useState, useEffect } from 'react'
export function useGetCoins ({ url }) {
const [getCoins, setGetCoins] = useState(null)
useEffect(() => {
window.fetch(url)
.then(res => res.json())
.then(json => setGetCoins(json))
.catch(e => new Error(e))
}, [url])
return { getCoins }
}
Asi queda la clase http
class Http {
static instance = new Http();
get = async url => {
try {
let req = await fetch(url);
let json = req.json();
return json;
} catch (error) {
console.log(`http get method: ${error}`);
throw Error(error);
}
};
post = async (url, body) => {
try {
let req = await fetch(url, {
method: 'POST',
body,
});
let json = req.json();
return json;
} catch (error) {
console.log(`http post method: ${error}`);
throw Error(error);
}
};
put = async (url, id, body) => {
try {
let req = await fetch(`${url}/${id}`, {
method: 'PUT',
body,
});
let json = req.json();
return json;
} catch (error) {
console.log(`http put method: ${error}`);
throw Error(error);
}
};
remove = async (url, id) => {
try {
let req = await fetch(`url/${id}`, {
method: 'DELETE',
});
let json = req.json();
return json;
} catch (error) {
console.log(`http put method: ${error}`);
throw Error(error);
}
};
}
export default Http;
Lo que yo copie del código de la clase: https://github.com/civilian/cryptoTracker/tree/19aa2cc98b6da24d4387904ee9c944fe406941bb
hasta el momento esta muy bueno el curso, listo para seguir aprendiendo
Asà se ve usando componentes funcionales y el hook useEffect
import React, {useEffect} from 'react';
import {Pressable, StyleSheet, Text, View} from 'react-native';
import Http from '../../libs/http';
const CoinsScreen = props => {
useEffect(() => {
Http.instance
.get('https://api.coinlore.net/api/tickers')
.then(coins => {
console.log('coins', coins);
})
.catch(err => {
console.log('errorrr', err);
});
}, []);
const handlePress = event => {
props.navigation.navigate('CoinDetail');
};
return (
<View style={styles.container}>
<Text style={styles.titleText}>Coins Screen</Text>
<Pressable onPress={handlePress} style={styles.btn}>
<Text style={styles.btnText}>Go to coins detail</Text>
</Pressable>
</View>
);
};
En windows si no pueden entrar al comand + m para el debug escriban esto en la consola donde arrancaron el android
adb shell input keyevent 82
Usando un custom hook
import React, { useState, useEffect } from 'react'
import { StyleSheet, Text, View, Pressable } from 'react-native'
import { useGetCoins } from '../hooks/useGetCoins'
export const CoinsScreen = ({ navigation }) => {
const { coins, loading } = useGetCoins()
console.log('{ coins, loading }',{ coins, loading });
const handlePess = () => {
navigation.navigate('CoinDetailScreen')
}
if(loading){
return <Text>Cargando...</Text>
}
return (
<View style={styles.container}>
<Text style={styles.titleText}>CoinsScreen </Text>
<Pressable style={styles.btn} onPress={handlePess}>
<Text style={styles.btnText}>Ir a detail</Text>
</Pressable>
</View>
)
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'red'
},
titleText: {
color: 'white',
textAlign: 'center'
},
btn: {
padding: 0,
backgroundColor: 'blue',
borderRadius: 8,
margin: 16
},
btnText: {
color: 'white',
textAlign: 'center'
}
})
En componentDidMount puedo ocuparlo de esta forma?, ya que es un método de la clase
async componentDidMount() {
}
El metodo delete y put serÃa mas o menos asÃ:
class Http {
static instance = new Http();
async get(url) {
try {
const req = await fetch(url);
const json = await req.json();
return json;
} catch (err) {
console.log('http get method err', err);
throw new Error(err);
}
}
async post(url, body) {
try {
const req = await fetch(url, {
method: 'POST',
body,
});
const json = req.json();
return json;
} catch (err) {
console.log('http post method err', err);
throw new Error(err);
}
}
async delete(url, id) {
try {
const req = await fetch(`${url}/${id}`, {
method: 'DELETE',
});
const json = req.json();
return json;
} catch (err) {
console.log('http post method err', err);
throw new Error(err);
}
}
async put(url, id, body) {
try {
const req = await fetch(`${url}/${id}`, {
method: 'PUT',
body,
});
const json = req.json();
return json;
} catch (err) {
console.log('http post method err', err);
throw new Error(err);
}
}
}
export default Http;
class Api {
constructor(endpoin) {
this.http = new Http();
this.base = endpoin;
}
get(method, headers = null) {
return this.http.get(`${this.base}${method}`, headers);
}
post(method, body, headers = null) {
return this.http.post(`${this.base}${method}`, body, headers);
}
put(method, body, headers = null) {
return this.http.put(`${this.base}${method}`, body, headers);
}
patch(method, body, headers = null) {
return this.http.patch(`${this.base}${method}`, body, headers);
}
delete(method, headers = null) {
return this.http.delete(`${this.base}${method}`, headers);
}
}
class Http {
get = async (url, headers = null) => {
try {
let res = await fetch(url, {...(headers ? {headers} : {})});
let json = await res.json();
return {...res, json};
} catch (err) {
console.log('http get method err', err);
throw Error(err);
}
};
post = async (url, body, headers = null) => {
try {
let res = await fetch(url, {
method: 'POST',
body,
...(headers ? {headers} : {}),
});
let json = await res.json();
return {...res, json};
} catch (err) {
console.log('http get method err', err);
throw Error(err);
}
};
put = async (url, body, headers = null) => {
try {
let res = await fetch(url, {
method: 'PUT',
body,
...(headers ? {headers} : {}),
});
let json = await res.json();
return {...res, json};
} catch (err) {
console.log('http get method err', err);
throw Error(err);
}
};
patch = async (url, body, headers = null) => {
try {
let res = await fetch(url, {
method: 'PATCH',
body,
...(headers ? {headers} : {}),
});
let json = await res.json();
return {...res, json};
} catch (err) {
console.log('http get method err', err);
throw Error(err);
}
};
delete = async (url, headers = null) => {
try {
let res = await fetch(url, {
method: 'DELETE',
...(headers ? {headers} : {}),
});
let json = await res.json();
return {...res, json};
} catch (err) {
console.log('http get method err', err);
throw Error(err);
}
};
}
const http = new Http();
export default Api;
export {http as Http};
Tengo un problema en la consola.
Me sale Type Error: Network Request Falled
Alguien más tiene el mismo problema?
se pueden utilizar los hooks en react native?
Excelente practica la que recomienda el profesor, en un proyecto grande, es algo tedioso tener que andar generando el fetch para cada llamada.
Seguimos 😃
Los aportes, preguntas y respuestas son vitales para aprender en comunidad. RegÃstrate o inicia sesión para participar.