onetomany
Freddy Heredia 2 years ago
parent 5c7c81270f
commit 82e6350aa0

@ -4,12 +4,12 @@ import LinearGradient from 'react-native-linear-gradient';
interface Props {
title:string,
onClick?(): void,
onPress?(): void,
style?: "primary" | "secundary" | "info",
additionalStyle?: string
}
export const Button:FC <Props> = ({title,onClick, style="primary",additionalStyle}) => {
export const Button:FC <Props> = ({title,onPress, style="primary",additionalStyle}) => {
let className = "rounded-full mx-8 p-4 shadow-xl shadow-slate-800 uppercase";
switch (style) {
@ -27,7 +27,7 @@ export const Button:FC <Props> = ({title,onClick, style="primary",additionalStyl
<>
<LinearGradient start={{x: 0, y: 0}} end={{x: 1, y: 0}} className={className} colors={['#7dd3fc', '#0ea5e9', '#2563eb']} >
<TouchableOpacity
onPress={onClick}
onPress={onPress}
>
<Text className='text-white text-center font-bold text-xl' >{title}</Text>
</TouchableOpacity>

@ -0,0 +1,20 @@
import React, { FC } from 'react';
import { View } from 'react-native'
type CardType = {
children: JSX.Element | JSX.Element[],
addClassName?: string
}
export const CardItem:FC<CardType> = ({ children , addClassName}) => {
let className = 'w-5/6 p-4 m-4 bg-white rounded-xl border border-slate-300';
className = className + " " + addClassName;
return (
<>
<View className={className}>
{children}
</View>
</>
)
}

@ -1,53 +1,38 @@
import React, { FC, useEffect, useState } from 'react'
import { Card } from '../Card'
import { FlatList, Text, TouchableOpacity } from 'react-native'
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth'
import { FlatList, RefreshControl, Text, TouchableOpacity } from 'react-native'
import { useNavigation } from '@react-navigation/native';
import { CardItem } from '../CardItem';
import { NativeStackNavigationProp } from '@react-navigation/native-stack';
interface Props {
endpoint: string
entities: [],
screenName: string
}
export const CardList:FC <Props> = ({endpoint}) => {
const navitation = useNavigation();
let defaultData:[] = [];
const [entities, setEntities] = useState(defaultData);
export const CardList:FC <Props> = ({entities, screenName}) => {
const navitation = useNavigation<NativeStackNavigationProp<any>>();
const getInitData = async () => {
const { data, error } = await useFetchWithAuth(endpoint);
if (!error) {
setEntities(data);
} else {
console.log(error)
}
}
useEffect(() => {
getInitData();
}, [endpoint])
return (
<>
<FlatList
data={entities}
renderItem={({item}) =>
<Card>
<CardItem>
<TouchableOpacity
onPress={()=>navitation.navigate("CustomerFormScreen" as never)}
onPress={()=>
navitation
.navigate(screenName , {id:item['id']} )}
>
<Text>
{item["nombre"]}
</Text>
</TouchableOpacity>
</Card>
</CardItem>
}
keyExtractor={item => item["id"]}
/>

@ -0,0 +1,42 @@
import AsyncStorage from "@react-native-async-storage/async-storage";
const fecher = async (url: string, id:string, token: string, data:any) => {
return await fetch(url, {
method: id==="0" ? 'POST': 'PATCH',
mode: 'cors',
headers: {
'Authorization' :token,
'Content-Type': 'application/json',
'Accept':'application/json'
},
body: data,
});
}
export const saveWithAuth = async (url: string, id:string, body:any) => {
url= "http://192.168.1.21:8082"+"/api/"+url+"/";
if ( Number(id)>0){
url = url + id +"/"
}
const token = await AsyncStorage.getItem('token') || "";
let data;
let error;
try{
data = JSON.stringify(body);
console.log(url)
const response = await fecher(url, id, token, data)
if (response.ok){
data = await response.json();
}else {
error = "Servidor: "+ ((await response.json()).trace).substring(1,300);
}
}catch (e){
error = "Cliente: "+e;
}
return {
data,
error
}
}

@ -11,6 +11,7 @@ import { ProductScreen } from '../screens/product/ProductScreen';
import { ExitScreen } from '../screens/exit/ExitScreen';
import { CustomerListScreen } from '../screens/customer/CustomerListScreen';
import { CustomerStack } from '../screens/customer/CustomerStack';
import CompanyStack from '../screens/company/CompanyStack';
interface Props {
@ -48,8 +49,8 @@ export const TabScreen:FC <Props> = () => {
}}
/>
<Tab.Screen
name="CompanyScreen"
component={CompanyScreen}
name="CompanyStack"
component={CompanyStack}
options={{
tabBarLabel: 'Compañias',
tabBarIcon: ({ focused}) => (

@ -0,0 +1,8 @@
const CompanyFormScreen = () => {
return(
<>
</>
)
}
export default CompanyFormScreen;

@ -0,0 +1,12 @@
import { Text } from "react-native";
const CompanyListScreen = () => {
return (
<>
<Text>Compañia lista</Text>
</>
)
}
export default CompanyListScreen;

@ -0,0 +1,24 @@
import { createNativeStackNavigator } from "@react-navigation/native-stack";
import CompanyListScreen from "./CompanyListScreen";
import CompanyFormScreen from "./CompanyFormScreen";
const Stack = createNativeStackNavigator();
const CompanyStack = () => {
return(
<Stack.Navigator
screenOptions={
{
headerShown:true
}
}
>
<Stack.Screen name="CompanyListScreen" component={CompanyListScreen} />
<Stack.Screen name="CompanyFormScreen" component={CompanyFormScreen}/>
</Stack.Navigator>
)
}
export default CompanyStack;

@ -1,4 +1,4 @@
import { FC } from 'react'
import { FC, useEffect } from 'react'
import { Text } from 'react-native'
import { NavBar } from '../../components/navbar/NavBar'
import { Background } from '../../components/Background'
@ -7,12 +7,70 @@ import { Button } from '../../components/Button';
import { Card } from '../../components/Card';
import { Input } from '../../components/Input';
import { useForm } from 'react-hook-form';
interface Props {
import { NativeStackScreenProps } from '@react-navigation/native-stack';
import { RootStackParams } from './CustomerStack';
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth';
import { saveWithAuth } from '../../hooks/saveWithAuth';
interface Props extends NativeStackScreenProps<RootStackParams, 'CustomerFormScreen'>{};
export const CustomerFormScreen = ({route , navigation }: Props) => {
const { control, handleSubmit, getValues, setValue, formState: { errors } } = useForm({
defaultValues: {
id: 0,
nombre: '',
telefono: '',
}
});
let id:string = "0";
if (route.params?.id!= undefined) {
id = String(route.params.id);
}
const getInitData = async () => {
if (!id || id=="0")
return;
const { data, error } = await useFetchWithAuth("cliente/" + id);
if (!error) {
if (data.id!=0){
setValue("id", data['id'])
setValue("nombre", data['nombre'])
setValue("telefono", data['telefono'])
}
} else {
console.log(error)
}
}
export const CustomerFormScreen:FC <Props> = () => {
const { control, handleSubmit, getValues, formState: { errors } } = useForm();
const navigation = useNavigation();
useEffect(() => {
getInitData();
}, [])
const onSubmit = async (entity: any) => {
try {
let endpoint = "cliente";
//entity['compania'] = {id: entity['compania']}
console.log(entity)
const { data, error } = await saveWithAuth(endpoint, id, entity);
if (error) {
console.log(error);
} else {
navigation.navigate("CustomerListScreen")
}
} catch (e) {
console.log("Post error:");
console.table(e);
}
}
console.debug(id)
return (
<>
<Background >
@ -22,7 +80,7 @@ export const CustomerFormScreen:FC <Props> = () => {
<Input name="telefono" label='Telefono' control={control} />
<Button
title='Guardar'
onClick={()=>{navigation.navigate("ProductScreen" as never) }}
onPress={handleSubmit(onSubmit)}
/>
</Card>

@ -1,27 +1,67 @@
import { FC } from 'react'
import { FlatList, Text, View } from 'react-native'
import { Background } from '../../components/Background'
import { FC, useEffect, useState } from 'react'
import { FlatList, RefreshControl, Text, View } from 'react-native'
import { Card } from '../../components/Card'
import { Button } from '../../components/Button'
import { useNavigation } from '@react-navigation/native';
import { CardList } from '../../components/cardList/CardList'
import { useFetchWithAuth } from '../../hooks/useFetchWithAuth'
interface Props {
}
export const CustomerListScreen:FC <Props> = () => {
const navigation = useNavigation();
const [refreshing, setRefreshing] = useState(false);
const endpoints = "cliente";
let defaultData:[] = [];
const [entities, setEntities] = useState(defaultData);
console.log("Inicio list customer")
const getInitData = async () => {
const { data, error } = await useFetchWithAuth(endpoints);
if (!error) {
setEntities(data);
} else {
console.log(error)
}
}
useEffect(() => {
console.log("Disparo useEffect list customer")
getInitData();
}, [refreshing])
const onRefresh = () => {
setRefreshing(true);
setTimeout(() => {
setRefreshing(false);
}, 1000);
};
return (
<View className=''>
<Button title=' + ' additionalStyle='z-10 absolute bottom-2 right-0' onClick={()=>navigation.navigate("CustomerFormScreen" as never)} />
<View className='bg-sky-100'>
<Button
title=' + '
additionalStyle='z-10 absolute bottom-2 right-0'
onPress={()=>navigation.navigate("CustomerFormScreen" as never)} />
<FlatList
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={onRefresh}
/>
}
data={[""]}
renderItem={({item}) =>
<View id={item} className='flex-1 items-center'>
<Card>
<Text className='text-xl text-center my-4'>Listado de clientes</Text>
<CardList endpoint='cliente'/>
<CardList screenName="CustomerFormScreen" entities={entities} />
</Card>
</View>

@ -1,14 +1,16 @@
import { FC, useContext, useState } from 'react'
import { useContext } from 'react'
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import { AuthContext } from '../login/AuthContext';
import { CustomerFormScreen } from './CustomerFormScreen';
import { CustomerListScreen } from './CustomerListScreen';
interface Props {
export type RootStackParams = {
CustomerListScreen: undefined,
CustomerFormScreen: {id:number}
}
const Stack = createNativeStackNavigator();
const Stack = createNativeStackNavigator<RootStackParams>();
export const CustomerStack:FC <Props> = () => {
export const CustomerStack = () => {
const {isAuthenticated} = useContext(AuthContext)
return (
@ -20,7 +22,7 @@ export const CustomerStack:FC <Props> = () => {
>
{isAuthenticated&&(
<>
<Stack.Screen name="Clientes" component={CustomerListScreen} />
<Stack.Screen name="CustomerListScreen" component={CustomerListScreen} />
<Stack.Screen name="CustomerFormScreen" component={CustomerFormScreen} />
</>
)}

@ -20,7 +20,7 @@ export const ExitScreen:FC <Props> = () => {
<Background >
<Text>Adios</Text>
<Button title='LogOut' onClick={()=>exit()} />
<Button title='LogOut' onPress={()=>exit()} />
</Background>

@ -56,7 +56,7 @@ export const LoginScreen:FC <Props> = ({ navigation }) => {
<InputPassword name="password" label='Contraseña' control={control}/>
<Button additionalStyle='my-auto' onClick={handleSubmit(onSubmit)} title='Login'/>
<Button additionalStyle='my-auto' onPress={handleSubmit(onSubmit)} title='Login'/>
</Card>
</Background>

Loading…
Cancel
Save