I'm trying to use props in function component. But the the function has navigation component in it like below.
const AddProductList = ({props, route, navigation}) => {
const {navData} = route.params;
var [data, setData] = useState(DATA);
...
...
...
}
because of route, navigation I think props is undefined.
I'm trying to write this example purely in functional style.
I need to do some thing like reading current data from flat list on tap.
var id = props.item.product_id_to_delete
because props is undefined I'm not getting item id to delete the tapped item.
Kindly anyone help me.
check full code
import React, {useState} from 'react';
import {View} from 'react-native-animatable';
import {
TextInput,
TouchableOpacity,
FlatList,
} from 'react-native-gesture-handler';
import Icon from 'react-native-vector-icons/FontAwesome';
import {StyleSheet, Pressable, Text, Button} from 'react-native';
import * as Animatable from 'react-native-animatable';
import Swipeout from 'react-native-swipeout';
import ButtonPressable from '../../components/ButtonPressable';
var sqlite_wrapper = require('./sqliteWrapper');
const DATA = [
{
prodName: 'Added data will look like this',
},
];
const AddProductList = ({item, route, navigation}) => {
const {navData} = route.params;
const [prodName, setProdName] = useState('');
var [data, setData] = useState(DATA);
const swipeSettings = {
style: {
marginBottom: 10,
},
autoClose: false,
backgroundColor: 'transparent',
close: false,
disabled: false,
onClose: (sectionID, rowId, direction) => {
console.log('---onclose--');
},
onOpen: (sectionID, rowId, direction) => {
console.log('---onopen--' + item);
},
right: [
{
backgroundColor: 'dodgerblue',
color: 'white',
text: 'Edit',
onPress: () => {
console.log('-----edit-----');
},
},
],
left: [
{
backgroundColor: 'red',
color: 'white',
text: 'Delete',
onPress: () => {
console.log('-----delete-----');
sqlite_wrapper.deleteById;
},
type: 'delete',
// component : (<ButtonPressable text="delete" />)
},
],
// buttonWidth: 100,
};
return (
<View style={styles.container}>
<Animatable.View
animation="bounceIn"
duration={1000}
style={styles.inputFieldView}>
<TextInput
style={styles.textInput}
onChangeText={(value) => setProdName(value)}
placeholder="Add the Product"
defaultValue={prodName}
/>
<TouchableOpacity
style={styles.addView}
onPress={() => {
sqlite_wrapper
.insert({prodName: prodName}, sqlite_wrapper.collection_product)
.then((result) => {
console.log('---result---');
console.log(result);
if (result.rowsAffected) {
fetchAllData();
}
});
function fetchAllData() {
sqlite_wrapper
.readAll(sqlite_wrapper.collection_product)
.then((resultData) => {
console.log('---resultData---');
console.log(resultData);
setData(resultData);
setProdName('');
});
}
// without sql this is how to update the state having a array
// const updatedArray = [...data];
// updatedArray.push({prodName: prodName});
// setData(updatedArray);
// setProdName('');
}}>
<Icon name="plus" size={16} style={styles.add} color="white" />
</TouchableOpacity>
</Animatable.View>
<Animatable.View
animation="bounceInLeft"
duration={1500}
style={{flex: 1}}>
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={({item, index}) => (
<Swipeout {...swipeSettings}>
<View style={styles.listView}>
<Text style={styles.listViewText}>{item.prodName}</Text>
</View>
</Swipeout>
)}
/>
</Animatable.View>
</View>
);
};
var styles = StyleSheet.create({
container: {
flex: 1,
},
inputFieldView: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch',
margin: 10,
},
textInput: {
flex: 1,
backgroundColor: '#b2ebf2',
borderTopLeftRadius: 7,
borderBottomLeftRadius: 7,
fontSize: 16,
},
addView: {
backgroundColor: '#0f4c75',
alignSelf: 'stretch',
alignItems: 'center',
justifyContent: 'center',
borderTopEndRadius: 7,
borderBottomEndRadius: 7,
padding: 9,
},
add: {
padding: 7,
},
listView: {
padding: 20,
backgroundColor: 'green',
margin: 0,
borderRadius: 0,
},
listViewText: {
color: 'white',
},
});
export default AddProductList;
change your component to this...
const AddProductList = ({item, route, navigation}) => {
const {navData} = route.params;
var [data, setData] = useState(DATA);
var id = item.product_id_to_delete
...
}
explanation: you are already doing object destruction, so props is all total i.e main parent, but navigation, route is the elements that
like:
props: {
navigation,
route,
...
}
Related
React, {useCallback, useState, useEffect, useRef} from 'react';
import {
View,
SafeAreaView,
FlatList,
Image,
Text,
TextInput,
TouchableOpacity,
StyleSheet,
ActivityIndicator,
} from 'react-native';
import Nodata from '../main/banking/common/Nodata';
import Icon from 'react-native-vector-icons/Ionicons';
import Toast from 'react-native-simple-toast';
import axios from 'axios';
import useSessionToken from '../hooks/useSessionToken';
import moment from 'moment';
import ListData from '../main/banking/common/ListData';
import {
widthPercentageToDP as wp,
heightPercentageToDP as hp,
} from 'react-native-responsive-screen';
import ShimmerPlaceholder from 'react-native-shimmer-placeholder';
import LinearGradient from 'react-native-linear-gradient';
function CustomerNotes(props) {
const session = useSessionToken();
const textInputRef = useRef();
const [notes, setNotes] = useState('');
const [data, setData] = useState({
notesList: [],
visible: false,
});
useEffect(() => {
getNotes();
}, [session,data]);
const getNotes = async () => {
try {
const qs = require('qs');
let params = qs.stringify({
cust_id: props.customerId,
operation: 'notes_list',
});
await axios
.post(
'https://abc.cdhgfhg.com/adghagsa',
params,
{
headers: {
Cookie: session?.token,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
if (response.data.status === 1) {
console.log('customernotes', response.data.data.hits.hits);
setData({
...data,
notesList: response.data.data.hits.hits,
visible: false,
});
}
})
.catch(function (error) {
console.log('CustomerNoteserror', error);
});
} catch (error) {
console.log('CustomerNoteserror', error);
}
};
const renderItem = ({item, index}) => {
var initialtv = Number(index + 1).toString();
var formattedDate = moment(item._source.added_on).format(
'ddd, MMM DD YYYY',
);
// console.log('initial', item, initialtv);
const data = {
text: item._source.notes,
mobile: formattedDate,
amount: '',
};
return <ListData item={data} />;
};
const handleInputSubmit = useCallback(ev => {
const input = ev.nativeEvent.text;
// validate all you want here
setNotes(input);
}, []);
const submitNotes = () => {
if (notes.length > 0) {
setData(prevState => ({
...prevState,
visible: true,
}));
addNotes();
} else {
Toast.show('Enter Notes');
}
};
const addNotes = async () => {
try {
const qs = require('qs');
let params = qs.stringify({
cust_id: props.customerId,
operation: 'add_notes',
notes: notes,
});
await axios
.post(
'https://abc.cdhgfhg.com/adghagsa',
params,
{
headers: {
Cookie: session?.token,
'Content-Type': 'application/x-www-form-urlencoded',
},
},
)
.then(function (response) {
if (response.data.status === 1) {
// console.log('addNotes', response.data);
getNotes();
}
})
.catch(function (error) {
console.log('addNoteserror', error);
});
} catch (error) {
console.log('CustomerNoteserror', error);
}
};
return (
<View style={{flex: 1, backgroundColor: 'white'}}>
{data.visible == true ? (
<ActivityIndicator
size="large"
color="#0096FF"
style={{
justifyContent: 'center',
alignItems: 'center',
position: 'absolute',
left: 0,
right: 0,
top: 0,
bottom: 0,
}}
/>
) : null}
{data.notesList.length != 0 ? (
<FlatList
data={data.notesList}
renderItem={renderItem}
style={{marginTop: hp('1.5%')}}
/>
) : (
<Nodata />
)}
<View
style={{
flex: 1,
flexDirection: 'row',
position: 'absolute',
bottom: 0,
marginBottom: '4%',
}}>
<TextInput
ref={textInputRef}
autoFocus={false}
style={styles.TextInputStyleClass}
placeholder="Write something"
placeholderTextColor={'#D0D0D0'}
onChangeText={
text => setNotes(text)
// (data.notes = text)
}
/>
<TouchableOpacity
onPress={() => submitNotes()}
style={{
height: 44,
width: 46,
backgroundColor: '#0096FF',
borderRadius: 6,
justifyContent: 'center',
alignItems: 'center',
elevation: 5,
marginRight: '4%',
}}>
<Icon
name={'send'}
size={20}
color="#ffffff"
style={{alignItems: 'center', justifyContent: 'center'}}
/>
</TouchableOpacity>
</View>
</View>
);
}
export default React.memo(CustomerNotes);
const styles = StyleSheet.create({
TextInputStyleClass: {
height: 45,
borderColor: '#0096FF',
flex: 7,
marginLeft: '4%',
marginRight: '4%',
flex: 1,
borderRadius: 6,
borderWidth: 1,
paddingLeft: 12,
fontFamily: 'Poppins-Medium',
fontSize: 14,
backgroundColor: 'white',
},
titleStyle: {
fontSize: 13,
color: '#000000',
fontFamily: 'Poppins-SemiBold',
},
subTitle: {
fontSize: 11,
fontFamily: 'Poppins',
color: '#000000',
},
});
I am fetching data from getNotes() API to render in Flatlist also I have a textinput at the bottom of the page. Whenever I submit textinput data to addNotes API data is added sucessfully and again I am calling getNotes API to reload the data in flatlist.
The issue is data rendering in flatlist is getting very slow and also the activityIndicator is not loading properly. When I call submitNotes the activityIndicator should start loading once the data is added and finished data rendering in flatlist the activityloader should stop loading.
To reload the flatlist each time the data changes you can pass extraData props. For performance optimizations, you can limit the number of items to be loaded at once using initialNumToRender, and onScroll more items will be loaded. Toggle refreshing props to true/false based on API response.
<FlatList
data={data.notesList}
renderItem={renderItem}
style={{marginTop: hp('1.5%')}}
keyExtractor={...}
extraData={data.noteList}
initialNumToRender={10}
refreshing={true}
/>
My code is working fine, it's pushing all the data to firebase as it should. I'm having no problems at all.
I just want to implement to remove the submitted data in text input. Since it stays there and you have to remove it manually.
I've been trying to add another function to 'onPress' to clear the inputs, but I can't seem to make it work. Any advice or help will be more than welcome.
Please check my code here below.
import { useState } from 'react';
import { StyleSheet, Text, View, TextInput, TouchableOpacity } from 'react-native';
import { addDoc, collection, doc, setDoc } from "firebase/firestore";
import { db } from './components/config';
export default function App() {
const [nombre, setNombre] = useState('');
const [cantidad, setCantidad] = useState('');
const [pretexto, setPretexto] = useState('');
function create(){
//Submit data
addDoc(collection(db, "users"), {
nombre: nombre,
cantidad: cantidad,
pretexto: pretexto
}).then(() => {
console.log('Data submitted');
}).catch((error) => {
console.log(error);
})
}
return (
<View style={styles.container}>
<View style={styles.textBox}>
<TextInput value ={nombre} onChangeText={(nombre) => {setNombre(nombre)}} placeholder='Nombre del caretubo' style={styles.inputOne}></TextInput>
<TextInput value={cantidad} onChangeText={(cantidad) => {setCantidad(cantidad)}} placeholder='Cantidad que debe el HP' style={styles.inputTwo}></TextInput>
<TextInput value={pretexto} onChangeText={(pretexto) => {setPretexto(pretexto)}} placeholder='Pretexto' style={styles.inputThree}></TextInput>
<TouchableOpacity style={styles.botonaso} onPress={() => {create; setNombre(''); }}>
<Text style={styles.botonasoTexto}>Subir</Text>
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
textBox: {
width: '100%',
padding: 12,
borderColor: 'gray',
borderWidth: 1,
borderRadius: 20,
},
inputOne: {
fontSize: 15,
},
inputTwo: {
fontSize: 15,
},
inputThree: {
fontSize: 15
},
botonaso: {
backgroundColor: '#202A44',
alignItems: 'center',
borderRadius: 20,
padding: 10
},
botonasoTexto: {
color: 'white'
}
});
const clearTextInputs = () => {
setNombre('');
setCantidad('');
setPretexto('');
};
function create() {
//Submit data
addDoc(collection(db, "users"), {
nombre: nombre,
cantidad: cantidad,
pretexto: pretexto
}).then(() => {
console.log('Data submitted');
clearTextInputs(); // <---------- add here
}).catch((error) => {
console.log(error);
})
}
<TouchableOpacity style={styles.botonaso} onPress={create}> // <----- onPress here
<Text style={styles.botonasoTexto}>Subir</Text>
</TouchableOpacity>
I want to use onScrollBegin on my flatlist. But everytime I make scroll the function runs. I only want to run this function when I am at the top, not everytime I scroll.
import * as React from 'react';
import { StyleSheet, Text, View, Pressable, Image, Dimensions, Platform, FlatList, TextInput } from 'react-native';
import { messages } from '../utils/mockChat';
import { useDispatch, useSelector } from 'react-redux';
import moment from 'moment';
import Modal from 'react-native-modalbox';
import { openModalImage } from '../redux/slice/chat/chatSlice';
const { width, height } = Dimensions.get('screen');
function propsEqual(prevProp, nextProp) {
if(prevProp.id === nextProp.id) {
return true;
}
}
const Item = React.memo(({ global_user_id, id, type, render, allDates, name, user_id, reciever, text, images, video, sending, pending, read, date }) => {
const dateNum = moment(date).format('DD-MM-YYYY');
return (
<View style={s.item}>
<View style={s.itemContainer}>
<View style={global_user_id === user_id ? s.ownerText : s.reciever_text}>
<Text style={s.text}>{ text }</Text>
</View>
</View>
</View>
)
}, propsEqual);
const userState = state => state.user.userID;
const modalState = state => state.chatSlice.modalImage;
const Chat = ({ route, navigation }) => {
const { image } = route.params;
const dispatch = useDispatch();
const modalSec = useSelector(modalState);
const userID = useSelector(userState);
const [message, setMessage] = React.useState(generateItems(messages));
const modalR = React.useRef(null);
const timerCloseModal = React.useRef(null);
React.useEffect(() => {
modalSec && modalR.current.open();
}, [modalSec]);
const dates = new Set();
function renderDate(date) {
dates.add(moment(date).format('DD-MM-YYYY'));
return (
<Text style={{color: '#333', fontSize: 12}}>{moment(date).format('DD-MM-YYYY')}</Text>
)
}
const showFooter = () => {
return (
<View style={s.footerContainer}>
<TextInput style={{height: 50, width: '100%', padding: 20}} />
</View>
)
};
const rowRenderer = ({ item }) => {
return (
<Item
item={item}
id={item.id}
allDates={dates}
render={(date) => renderDate(date)}
global_user_id={userID}
name={item.name}
user_id={item.user_id}
reciever={item.reciever}
text={item.text}
images={item.images}
video={item.video}
sending={item.sending}
pending={item.pending}
read={item.read}
type={item.type}
date={item.date} />
)
};
const closeModalImage = React.useCallback(() => {
dispatch(openModalImage());
}, [dispatch, modalR]);
return (
<View style={s.container}>
<FlatList
data={message}
keyExtractor={i => i.id.toString()}
renderItem={rowRenderer}
initialNumToRender={10}
onScrollBeginDrag={() => {
console.log('s');
// setMessage(items);
}}
extraData={message}
ListHeaderComponent={showFooter}
inverted
/>
</View>
)
};
const s = StyleSheet.create({
container: {
flex: 1
},
modal: {
justifyContent: 'center',
alignItems: 'center',
width: 300,
height: 300,
borderRadius: 200,
backgroundColor: 'transparent',
maxHeight: 500,
},
item: {
backgroundColor: 'red',
height: 250,
width: width * 0.8,
marginVertical: 12
},
ownerText: {
alignSelf: 'flex-end',
backgroundColor: 'blue'
},
reciever_text: {
alignSelf: 'flex-start'
}
});
export default Chat;
How can I fix it, that I can only scroll if I am on the top? I use inverted so its hard for me, to know where is the top position. I am very thankful for your help
Make use of the onEndReached prop.
The onEndReached function calls every time you reach the end of a list.
official doc
I am new to ReactNative programming and .tsx files in general. I'm trying to display a basic FlatList and have copied the below code from the ReactNative docs here: (https://reactnative.dev/docs/flatlist). It's only slightly modified to fit into my ReactNative app which I am editing in Visual Studio code.
Does anyone know the correct way to display a FlatList? I've spent 2-3 days tinkering with this but I'm obviously missing some crucial ingredient. Beats me.
import * as React from "react";
import { useState, Component } from "react";
import EditScreenInfo from "../components/EditScreenInfo";
import { StyleSheet, Text, View, Dimensions, TouchableOpacity, Alert, FlatList, SafeAreaView, StatusBar } from "react-native";
// import PaymentScreen from "./PaymentScreen";
import { Driver } from "../models/Driver";
// tslint:disable-next-line:typedef
const styles = StyleSheet.create({
page: {
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: "#FFF"
},
container: {
height: 750,
width: 750,
backgroundColor: "tomato"
},
map: {
flex: 1,
height:750,
width:750
},
item: {
padding: 10,
fontSize: 18,
height: 44,
},
title: {
fontSize: 18
}
});
// tslint:disable-next-line: typedef
const DATA = [
{
id: "bd7acbea-c1b1-46c2-aed5-3ad53abb28ba",
title: "First Item",
},
{
id: "3ac68afc-c605-48d3-a4f8-fbd91aa97f63",
title: "Second Item",
},
{
id: "58694a0f-3da1-471f-bd96-145571e29d72",
title: "Third Item",
},
];
// tslint:disable-next-line:typedef
const Item = ({ item, onPress, backgroundColor, textColor }: {
item: any;
onPress: any;
backgroundColor: any;
textColor: any;
}) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.title}</Text>
</TouchableOpacity>
);
export default class TabFourScreen extends Component {
drivers: Driver[] = []; // fetch these from backend... for now you can STUB
selectedId: any = useState(null);
setSelectedId: any = useState(null);
renderItem: any = ({ item }: {item: any}) => {
// tslint:disable-next-line:typedef
const backgroundColor = item.id === this.selectedId ? "#6e3b6e" : "#f9c2ff";
// tslint:disable-next-line:typedef
const color = item.id === this.selectedId ? "white" : "black";
return (
<Item
item={item}
onPress={() => this.setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
}
render = () => {
return (
<View style={styles.page}>
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={this.renderItem}
keyExtractor={(item) => item.id}
extraData={this.selectedId}
/>
</SafeAreaView>
</View>
);
}
}
First of all you can't use hooks like useState in a Class Component, you have to use Function Component: https://reactnative.dev/docs/getting-started#function-components-and-class-components.
Secondly, you have set width: 750 to your SafeAreaView's style, so the text doesn't appear on the screen you see but appears before.
Try this code:
import * as React from 'react';
import { useState, Component } from 'react';
import {
StyleSheet, Text, View, Dimensions, TouchableOpacity, Alert, FlatList, SafeAreaView, StatusBar,
} from 'react-native';
// import PaymentScreen from "./PaymentScreen";
// tslint:disable-next-line:typedef
const styles = StyleSheet.create({
page: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF',
},
container: {
height: 750,
width: '100%',
backgroundColor: 'tomato',
},
map: {
flex: 1,
height: 750,
width: 750,
},
item: {
height: 44,
},
title: {
fontSize: 25,
color: 'white',
},
});
// tslint:disable-next-line: typedef
const DATA = [
{
id: 'bd7acbea-c1b1-46c2-aed5-3ad53abb28ba',
title: 'First Item',
},
{
id: '3ac68afc-c605-48d3-a4f8-fbd91aa97f63',
title: 'Second Item',
},
{
id: '58694a0f-3da1-471f-bd96-145571e29d72',
title: 'Third Item',
},
];
// tslint:disable-next-line:typedef
const Item = ({
item, onPress, backgroundColor, textColor,
}) => (
<TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
<Text style={[styles.title, textColor]}>{item.title}</Text>
</TouchableOpacity>
);
const TabFourScreen = () => {
const [selectedId, setSelectedId] = useState(null);
const renderItem = ({ item }) => {
// tslint:disable-next-line:typedef
const backgroundColor = item.id === selectedId ? '#6e3b6e' : '#f9c2ff';
// tslint:disable-next-line:typedef
const color = item.id === selectedId ? 'white' : 'black';
return (
<Item
item={item}
key={item.id}
onPress={() => setSelectedId(item.id)}
backgroundColor={{ backgroundColor }}
textColor={{ color }}
/>
);
};
return (
<View style={styles.page}>
<SafeAreaView style={styles.container}>
<FlatList
data={DATA}
renderItem={renderItem}
keyExtractor={(item) => item.id}
extraData={selectedId}
/>
</SafeAreaView>
</View>
);
};
export default TabFourScreen;
I removed typescript just to test, feel free to add it again.
don't use this.renderItem use only renderItem
Hi I have a add minus component button that I want to pass the value to selected value to the "To Cart" button. If the value is zero the orders will not be added but if the value is > 0 then it will be added to cart.
below is my Add Minus button component
AddMinusButton.js
import React, { useState } from "react";
import { View, TouchableOpacity, Text, StyleSheet } from "react-native";
import Colors from "../../constants/Colors";
const AddMinusButton = () => {
const [value, setValue] = useState(0);
const minusValue = () => {
if (value > 0) {
setValue(value - 1);
} else {
setValue(0);
}
};
const plusValue = () => {
setValue(value + 1);
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.buttonLeft} onPress={minusValue}>
<Text>-</Text>
</TouchableOpacity>
<Text style={styles.quantity}> {value}</Text>
<TouchableOpacity style={styles.buttonRight} onPress={plusValue}>
<Text>+</Text>
</TouchableOpacity>
</View>
);
};
const styles = StyleSheet.create({
container: {
flexDirection: "row",
alignItems: "center",
borderWidth: 1,
borderRadius: 10,
height: 35,
overflow: "hidden",
borderColor: "black",
},
quantity: {
paddingHorizontal: 10,
marginRight: 3,
},
buttonLeft: {
alignItems: "center",
backgroundColor: Colors.primary,
borderRightWidth: 1,
borderRightColor: "black",
padding: 10,
},
buttonRight: {
alignItems: "center",
backgroundColor: Colors.primary,
borderLeftWidth: 1,
borderLeftColor: "black",
padding: 10,
},
});
export default AddMinusButton;
This is my Product Screen. I want to pass the value that is selected by the AddMinusButton component to the "To Cart". I am only able to made the button click and it will add one by one.
ProductOverviewScreen.js
import React, { useState, useEffect, useCallback } from "react";
import {
View,
Text,
FlatList,
Button,
Platform,
ActivityIndicator,
StyleSheet,
} from "react-native";
import { useSelector, useDispatch } from "react-redux";
import { HeaderButtons, Item } from "react-navigation-header-buttons";
import HeaderButton from "../../components/UI/HeaderButton";
import ProductItem from "../../components/shop/ProductItem";
import * as cartActions from "../../store/actions/cart";
import * as productsActions from "../../store/actions/products";
import Colors from "../../constants/Colors";
import * as AddMinusButton from "../../components/UI/AddMinusButton";
const ProductsOverviewScreen = (props) => {
const [isLoading, setIsLoading] = useState(false);
const [isRefreshing, setIsRefreshing] = useState(false);
const [error, setError] = useState();
const products = useSelector((state) => state.products.availableProducts);
const dispatch = useDispatch();
const loadProducts = useCallback(async () => {
setError(null);
setIsRefreshing(true);
try {
await dispatch(productsActions.fetchProducts());
} catch (err) {
setError(err.message);
}
setIsRefreshing(false);
}, [dispatch, setIsLoading, setError]);
useEffect(() => {
const willFocusSub = props.navigation.addListener(
"willFocus",
loadProducts
);
return () => {
willFocusSub.remove();
};
}, [loadProducts]);
useEffect(() => {
setIsLoading(true);
loadProducts().then(() => {
setIsLoading(false);
});
}, [dispatch, loadProducts]);
const selectItemHandler = (id, title) => {
props.navigation.navigate("ProductDetail", {
productId: id,
productTitle: title,
});
};
if (error) {
return (
<View style={styles.centered}>
<Text>An error occurred!</Text>
<Button
title="Try again"
onPress={loadProducts}
color={Colors.primary}
/>
</View>
);
}
if (isLoading) {
return (
<View style={styles.centered}>
<ActivityIndicator size="large" color={Colors.primary} />
</View>
);
}
if (!isLoading && products.length === 0) {
return (
<View style={styles.centered}>
<Text>No products found. Maybe start adding some!</Text>
</View>
);
}
return (
<FlatList
onRefresh={loadProducts}
refreshing={isRefreshing}
data={products}
keyExtractor={(item) => item.id}
renderItem={(itemData) => (
<ProductItem
image={itemData.item.imageUrl}
title={itemData.item.title}
price={itemData.item.price}
onSelect={() => {
selectItemHandler(itemData.item.id, itemData.item.title);
}}
>
<AddMinusButton />
<Button
color={Colors.primary}
title="To Cart"
onPress={() => {
dispatch(cartActions.addToCart(itemData.item));
}}
/>
</ProductItem>
)}
/>
);
};
ProductsOverviewScreen.navigationOptions = (navData) => {
return {
headerTitle: "All Products",
headerLeft: (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Menu"
iconName={Platform.OS === "android" ? "md-menu" : "ios-menu"}
onPress={() => {
navData.navigation.toggleDrawer();
}}
/>
</HeaderButtons>
),
headerRight: (
<HeaderButtons HeaderButtonComponent={HeaderButton}>
<Item
title="Cart"
iconName={Platform.OS === "android" ? "md-cart" : "ios-cart"}
onPress={() => {
navData.navigation.navigate("Cart");
}}
/>
</HeaderButtons>
),
};
};
const styles = StyleSheet.create({
centered: { flex: 1, justifyContent: "center", alignItems: "center" },
});
export default ProductsOverviewScreen;