if statement returns false every time - javascript

function Carts() {
let cartEval = [];
const cartData = useSelector((state) => state.cartProducts);
cartEval = cartData.map((item) => evalCart(item));
function evalCart(a) {
if (cartEval.find((b) => b.id == a.id)) {
return { ...b, numOfTimes: numOfTimes + 1 };
} else {
return {
id: a.id,
numOfTimes: 1,
prodTitle: a.title,
price: a.price,
};
}
}
const totalPrice = cartData
.map((item) => item.price)
.reduce((x, y) => x + y, 0);
function cartRender({ item }) {
return (
<View>
<View>
<View>
<Text>{item.numOfTimes}</Text>
<Text>{item.prodTitle}</Text>
<Text>{item.price}</Text>
<Text>Delete Button</Text>
</View>
</View>
</View>
);
}
return (
<View>
<View>
<Text>Total Sum of Items:{totalPrice}</Text>
</View>
<FlatList data={cartEval} renderItem={cartRender} />
</View>
);
}
const styles = StyleSheet.create({});
export default Carts;
This is what I want to achieve:
I need the function evalCart(a) to check if the item.id exist in the cartEval. If the id exists, increase item.nuofItems by 1. If it does not, create a new item with the id in the cartEval array.
But every time the function is called it returns false, hence the first part of the if statement never executes. only the else part. What am I doing wrong?

I was finally able to solve the puzzle. This is my solution below
function Carts() {
let cartEval = [];
const cartData = useSelector((state) => state.cartProducts);
cartData.map((item) => evalCart(item));
function evalCart(a) {
if (cartEval.find((b) => b.id == a.id)) {
const dummy = cartEval.filter((d) => d.id == a.id)[0];
cartEval.splice(cartEval.indexOf(dummy), 1, {
...dummy,
numOfTimes: dummy.numOfTimes + 1,
});
} else {
cartEval.push({
id: a.id,
numOfTimes: 1,
prodTitle: a.title,
price: a.price,
});
}
}
const totalPrice = cartData
.map((item) => item.price)
.reduce((x, y) => x + y, 0);
function cartRender({ item }) {
return (
<View>
<View>
<View>
<Text>{item.numOfTimes}</Text>
<Text>{item.prodTitle}</Text>
<Text>{item.price}</Text>
<Text>Delete Button</Text>
</View>
</View>
</View>
);
}
return (
<View>
<View>
<Text>Total Sum of Items:{totalPrice}</Text>
</View>
<FlatList data={cartEval} renderItem={cartRender} />
</View>
);
}
const styles = StyleSheet.create({});
export default Carts;
Thanks for your contributions

Related

Search Funtion in An Array React.js

I have an array of universities
And I need to make a search funtion.
My search implementation works perfectly and finds the university that I type.
However when I select the option, it confuses itself and always select by new index.
For example my array is ["A.T. Still University", "Abilene Christian University", "Abraham Baldwin University", "Academy for Five Element University" ... ]
In here, A.T. Still University is at the 0 index originally. and when I make a search with filter, it creates a new array. I type "Abilene" for example and it brings me a new array with results and "Abilene" becomes at the 0 index. However it doesnt select this one and keeps selecting "A.T. Still University" which has the original 0 index.
Can someone help me how to fix this problem ?
I want to be able to select what I type in search area.
My code is below
const SignupStep5 = forwardRef((props, ref) => {
const dispatch = useDispatch();
const userInfo = useSelector(state => state.profile.user);
const universityList = useSelector(state => state.config.universities);
const isFetchingUniversity = useSelector(state =>
isLoadingSelector([fetchUniversities], state),
);
//State
const [
selectedUniversityId,
setSelectedUniversityId,
selectedUniversityIdRef,
] = useStateRef(null);
const [choosenUniversity, setChoosenUniversity, choosenUniversityRef] =
useStateRef('');
const [choosenUniversityId, setChoosenUniversityId, choosenUniversityIdRef] =
useStateRef('');
useEffect(() => {
if (universityList.length) {
if (props.activeIndex == 5 && userInfo && userInfo.university) {
const index = universityList.findIndex(university =>
isEqual(university, userInfo.university),
);
if (index !== -1) {
setSelectedUniversityId(index);
setChoosenUniversity(userInfo.university);
}
}
}
}, [universityList]);
const renderHeader = () => (
<View>
<View style={styles.modalHeaderContainer}>
<Text style={styles.modalHeaderText}>
{strings.aboutMe.selectUniversity}
</Text>
<Touchable
style={styles.modalHeaderTextContainer}
onPress={() => {
if (selectedUniversityIdRef.current != null) {
setChoosenUniversityId(selectedUniversityIdRef.current);
setChoosenUniversity(
universityList[selectedUniversityIdRef.current],
);
closeBottomSheet();
}
}}>
<Text style={styles.modalHeaderSelectText}>
{strings.common.select}
</Text>
</Touchable>
</View>
<View style={styles.modalHeaderLine}></View>
</View>
);
const renderItem = ({item, index}) => (
<Touchable
style={
selectedUniversityIdRef.current === index
? styles.modalChildContainerSelected
: styles.modalChildContainer
}
onPress={() => handleSelection(index)}>
<Text style={styles.modalChildText}>{item}</Text>
</Touchable>
);
const handleSelection = id => {
const selectedId = selectedUniversityIdRef.current;
if (selectedId === id) setSelectedUniversityId(null);
else setSelectedUniversityId(id);
};
const onOverlayPress = () => {
if (choosenUniversityRef.current) {
const index = universityList.findIndex(
university => university === choosenUniversityRef.current,
);
if (index !== -1) {
setSelectedUniversityId(index);
}
} else if (
selectedUniversityIdRef.current != null &&
!choosenUniversityRef.current
) {
setSelectedUniversityId(null);
}
setModalVisible(false);
};
const [searchField, setSearchField] = useState('');
const searchInputFields = () => {
const filteredUniversity = universityList.filter(value => {
return value.toLowerCase().includes(searchField.toLowerCase());
});
return filteredUniversity;
};
return (
<>
<Portal>
{props.activeIndex == 5 && (
<BottomSheet
ref={bottomSheetRef}
snapPoints={snapPoints}
handleComponent={renderHeader}
backdropComponent={renderBackdrop}
onAnimate={handleSheetChanges}>
<TextInput
onChangeText={value => setSearchField(value)}
value={searchField}
style={{padding: 10, alignSelf: 'center'}}
placeholder="Search"
placeholderTextColor={'gray'}
/>
<BottomSheetFlatList
data={searchField ? searchInputFields() : universityList}
keyExtractor={(item, index) => index.toString()}
renderItem={renderItem}
contentContainerStyle={styles.modalChildStyle}
extraData={selectedUniversityIdRef.current}
/>
</BottomSheet>
)}
</Portal>
</>
);
});
export default SignupStep5;

How to edit item in a Flatlist

I made a Flatlist and and edit button that can open a modal to a text input and track down the key of the specific item. How do I update this item in the Flatlist with the different text input. I tried doing something with the setJournal but I don't know how to return it with the edited entry.
export default function HomeScreen({ navigation }) {
const [journal, setJournal] = useState([
{ date: "12-dec22", entry: "good day", key: "1" },
{ date: "12-dec22", entry: "bad day", key: "2" },
]);
const [editModal, setEditModal] = useState(false);
const handleEditPress = (key) => {
const currentJournal = journal.find((journn) => {
return journn.key === key;
});
setEditModal(true);
console.log(key);
};
const updateEntry = (key, entry) => {
if (journal.key === key) {
setJournal((currentJournal) => {
return [entry, ...currentJournal];
});
} else {}
journal = journal.map((journn) =>
journn.key === key ? { ...journn, ...updateEntry } : journn
);
};
return (
<View>
<Modal visible={editModal}>
<TextInput onChangeText={() => updateEntry()} />
<MaterialIcons name="close" onPress={() => setEditModal(false)} />
</Modal>
<View>
<MaterialIcons onPress={() => setModalOpen(true)}/>
<MaterialIcons onPress={() => deleteAll()} />
</View>
<FlatList
data={journal}
renderItem={({ item }) => (
<View style={styles.flatlistView}>
<TouchableOpacity>
<View>
<MaterialIcons onPress={() => handleEditPress(item.key)}/>
</View>
</TouchableOpacity>
</View>
)}
/>
</View>
);
}
const handleEditPress = (editedField, itemKey)=>{
journal.filter((currentItem.key)=>{(currentItem.key) === itemKey})).text = editedField
setJournal(journal)
}

todos not loading while using AsyncStorage

I am trying to use AsyncStorage to fetch my todos from inside the useEffect hook. If there are no todos(Meaning todos === []) Then a Text Component shows saying "Add a todo".
App image in expo
Initially the todos are set to "[]" inside the useState hook. When the addItem() method is called onPress the todos are not loading.
I do not know why this is happening...
export default function App() {
const [todo, setTodo] = useState('');
const [todos, setTodos] = useState([]);
useEffect(() => {
_retrieveData();
}, [todos]);
const addItem = (newTodo) => {
if (newTodo.length === 0) {
Alert.alert(
'Enter a String',
'You have entered a string with 0 characters',
[{ text: 'Okay', style: 'default' }]
);
} else {
console.log(newTodo);
let newTodos = [newTodo, ...todos];
setTodo('');
_storeData(JSON.stringify(newTodos));
}
};
const deleteTodo = (idx) => {
setTodos(todos.filter((todo, id) => id !== idx));
};
const _storeData = async (value) => {
try {
await AsyncStorage.setItem('TASKS', value);
} catch (error) {
// Error saving data
console.log(e);
}
};
const _retrieveData = async () => {
try {
const value = await AsyncStorage.getItem('TASKS');
if (value !== null) {
// We have data!!
setTodos(JSON.parse(value));
console.log(value);
}
} catch (error) {
// Error retrieving data
console.log(error);
}
};
return (
<TouchableWithoutFeedback
onPress={() => {
Keyboard.dismiss();
}}
>
<View style={styles.outerContainer}>
<Text style={styles.header}>TODO</Text>
<View style={styles.container}>
<TextInput
placeholder='new todo'
style={styles.input}
value={todo}
onChangeText={(text) => {
setTodo(text);
}}
></TextInput>
<Button title='Add' onPress={() => addItem(todo)}></Button>
</View>
<ScrollView style={styles.scrollView}>
{todos === [] ? (
<View>
<Text>Add a todo!</Text>
</View>
) : (
todos.map((todo, idx) => (
<View style={styles.todo} key={idx}>
<Text style={styles.todoText}>{todo}</Text>
<View style={styles.delete}>
<Button
color='red'
title='Delete'
onPress={() => deleteTodo(idx)}
></Button>
</View>
</View>
))
)}
</ScrollView>
</View>
</TouchableWithoutFeedback>
);
}
Dont use passed todo value newTodo, as setState is async dont get executed immediately, so you can use current setted todo value instead passed old value,
const addItem = (newTodo) => {
if (todo.length === 0) {
Alert.alert(
'Enter a String',
'You have entered a string with 0 characters',
[{ text: 'Okay', style: 'default' }]
);
} else {
console.log(todo);
let newTodos = [todo, ...todos];
setTodo('');
_storeData(JSON.stringify(newTodos));
setTodos(newTodos);
}
};

Not geting data from return inside firebase database

I am getting data from the firebase but able to it on emulator I tried using consloe which workfine
const Getdata = async () => {
await firebase.database().ref(`/orders/${user1.uid}`)
.on("child_added", (snapshot, key) => {
if(snapshot.key) {
console.log('key',snapshot.key);
let grabbedData = snapshot.val().orders;
grabbedData.map((order, i) => {
console.log('order',order.id);
console.log('order',order.avatar);
console.log('order',order.name);
console.log('order',order.price);
console.log('----------------');
});
}
});
}
Getdata();
After modifing the above code as below code nothing is showing to the screen
const Getdata = () => {
let data = firebase.database().ref(`/orders/${user1.uid}`)
.on("child_added", (snapshot, key) => {
// something is wrong with this below statememnt I think
return (
<Card>
<Text>{snapshot.key}</Text>
{
snapshot.val().orders.map((order, i) => {
return (
<TouchableOpacity key={i} onPress={() => {
}}>
<Card>
<View style={styles.user}>
<Image
style={styles.image}
resizeMode="cover"
source={{ uri: order.avatar }}
/>
<View style={{flexDirection:'column', flex: 1}}>
<Text style={styles.name} h4>{order.name}</Text>
<Card.Divider style={{ marginTop: 25}}/>
<View style={{flexDirection:'row', flex: 1,justifyContent: 'space-between'}}>
<Text style={styles.price}>{order.price}</Text>
</View>
</View>
</View>
</Card>
</TouchableOpacity>
);
})
}
</Card>
)
})
return data;
}
and then <Getdata/>
Something I am doing wrong with first return statememnt but dont know what.
Edit I am adding a pic how data is organised
Try this way
const [orders, setOrders] = useState([]); // initially empty
const [key, setKey] = useState(undefined); // undefined empty
const Getdata = async () => {
await firebase.database().ref(`/orders/${user1.uid}`)
.on("child_added", (snapshot, key) => {
if(snapshot.key) {
console.log('key',snapshot.key);
let grabbedData = snapshot.val().orders;
setKey(snapshot.key); // set key here
setOrders(grabbedData); // set orders here to state, it will rerender
}
});
}
useEffect(() => {
Getdata();
});
return (
<Card>
{key && <Text>{snapshot.key}</Text>}
{
orders.map((order, i) => {
return (
<TouchableOpacity key={i} onPress={() => {
}}>
.........
</TouchableOpacity>
);
})
}
</Card>
)

React Native , unable to add item in cart by using react -redux

I created a cart screen and list of items using react native and redux, but when I click buy item is not adding in cart and it's also not showing any error
Below is my code where I store list of items
Jeans.js
class Jeans extends Component {
render() {
return (
<View style={styles.container}>
<FlatList
data={this.props.items}
key={(items) => items.id.toString()}
numColumns={2}
renderItem={({ item }) => (
<CardBuyItem>
<Image style={styles.image} source={item.image} />
<View style={styles.detailContainer}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.subTitle} numberOfLines={1}>
{item.subTitle}
</Text>
<Text style={styles.price}>Rs {item.price}</Text>
</View>
<TouchableHighlight onPress={() => this.props.addToCart(item.id)}>
<View style={styles.buy}>
<Text>Buy Once</Text>
</View>
</TouchableHighlight>
</CardBuyItem>
)}
/>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.clothes.jeans,
};
};
const mapDispatchToProps = (dispatch) => {
return {
addToCart: (id) => dispatch(addToCart(id)),
};
};
Below is my code of cart screen where items should added when user click by
cart.js
class Cart extends Component {
render() {
let addedItems =
this.props.items && this.props.items.length ? (
<FlatList
data={this.props.items}
key={(items) => items.id.toString()}
numColumns={2}
renderItem={({ item }) => (
<View>
<Image style={styles.image} source={item.image} />
<View style={styles.detailContainer}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.subTitle} numberOfLines={1}>
Quantity: {item.quantity}
</Text>
<Text style={styles.price}>Rs {item.price}</Text>
</View>
<TouchableOpacity>
<View style={styles.buy}>
<Text>Remove</Text>
</View>
</TouchableOpacity>
</View>
)}
/>
) : (
<View style={styles.emptyContainer}>
<Text style={styles.empty}>There is Nothing in your Cart</Text>
</View>
);
return (
<View style={styles.container}>
<View style={styles.order}>
<Text style={styles.orderText}>You Order:</Text>
</View>
<View>{addedItems}</View>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.addedItems,
};
};
And below is my code reducer and action
reducer.js
export default function ClothesReducer(state = initialstate, action) {
if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find((item) => item.id === action.id);
let existed_item = state.addedItems.find((item) => action.id === item.id);
if (existed_item) {
addedItem.quantity += 1;
return {
...state,
total: state.total + addedItem.price,
};
} else {
addedItem.quantity = 1;
let newTotal = state.total + addedItem.price;
return {
...state,
addedItems: [...state.addedItems, addedItem],
total: newTotal,
};
}
} else {
return state;
}
}
action.js
import { ADD_TO_CART } from "./ClothesActionType";
export const addToCart = (id) => {
return {
type: ADD_TO_CART,
id,
};
};
I'm trying to figure out what's wrong but can't find any error. Can someone help me to fix this?
In cart.js you should replace this
const mapStateToProps = (state) => {
return {
items: state.addedItems,
};
};
With
const mapStateToProps = (state) => {
return {
items: state.clothes.addedItems,
};
};
You are mutating state, here is some info on how to not do that.
I think your reducer should look something like this:
export default function ClothesReducer(
state = initialstate,
action
) {
if (action.type === ADD_TO_CART) {
let addedItem = state.jeans.find(
(item) => item.id === action.id
);
let existed_item = state.addedItems.find(
(item) => action.id === item.id
);
const addedItems = existed_item
? state.addedItems.map((item) =>
item === existed_item
? { ...item, quantity: item.quantity + 1 }
: item
)
: [
...state.addedItems,
{ ...addedItem, quantity: 1 },
];
return {
...state,
addedItems,
total: state.total + addedItem.price,
};
} else {
return state;
}
}

Categories

Resources