#gorhom/bottom-sheet not closing on index change - react-native

I have the bottom sheet set up with a login form in it:
import { useContext, useMemo, useRef } from "react";
import { GeneralContext } from "#/providers";
import BottomSheet from "#gorhom/bottom-sheet";
import LoginForm from "./LoginForm";
const AuthSheet = () => {
const { showAuthModal } = useContext(GeneralContext);
const bottomSheetRef = useRef(null);
// variables
const snapPoints = useMemo(() => ["30%"], []);
const index = useMemo(() => {
if (showAuthModal) {
return 0;
}
return -1;
}, [showAuthModal]);
return (
<BottomSheet
ref={bottomSheetRef}
index={index}
enablePanDownToClose={true}
snapPoints={snapPoints}
>
<LoginForm />
</BottomSheet>
);
};
export default AuthSheet;
Whenever the user logs in, the showAuthModal is set to false and the index will be set to -1 again. The Sheet however does not close at all. The other way around does work, if I use some button somewhere in my app to set the showAuthModal to true, the sheet will open. Could this be because I am calling the context from a child component that it doesn't work?

It looks like the index prop is only used to determine the initial position of the sheet, so its possible that BottomSheet only uses index for the initial render and ignores it entirely after that. Try using the bottomSheetRef for closing on auth changes:
const AuthSheet = () => {
const { showAuthModal } = useContext(GeneralContext);
const bottomSheetRef = useRef(null);
// variables
const snapPoints = useMemo(() => ["30%"], []);
useEffect(() => {
if (!showAuthModal) {
bottomSheetRef.current?.close?.()
}
}, [showAuthModal]);
return (
<BottomSheet
ref={bottomSheetRef}
index={showAuthModal ? 0 : -1}
enablePanDownToClose={true}
snapPoints={snapPoints}
>
<LoginForm />
</BottomSheet>
);
};

Related

Display all posts from database

I have a Firestore collection, schemed as follows:
posts{
uid{
userPosts{
postID{
creation:
postText:
}
}
}
}
I want to display all of the posts, so I've made the corresponding queries and saved them in posts - an array of all the posts that I later iterate through.
The problem with the way I do it is that it keeps adding the same posts every render. So I've tried to set the array each time, but that way the code never passes through these posts && posts.length > 0 condition.
I'm really new to RN and JS in general, but what I was expecting is
Nothing to show here
at first, and then the list of posts.
The complete component:
import { Text, Pressable, FlatList, SafeAreaView } from "react-native";
import { globalStyles } from "../../styles/global";
import React, { useState, useEffect } from "react";
import { db } from "../../../firebase";
import Post from "../../API/Post";
import { collection, getDocs } from "firebase/firestore";
const FeedScreen = ({ navigation }) => {
const [posts, setPosts] = useState([]);
useEffect(() => {
const getPostData = async () => {
setPosts([]); // ---> Without this line the posts keeps adding each render
const q = collection(db, "posts");
const docSnap = await getDocs(q);
docSnap.docs.map(async (item) => {
const tmp = collection(db, "posts", item.id, "userPosts");
const tmpSnap = await getDocs(tmp);
tmpSnap.docs.map(async (element) => {
setPosts((prev) => {
prev.push(element.data());
return prev;
});
});
});
};
getPostData().catch(console.error);
return;
}, []);
return (
<SafeAreaView style={globalStyles.global}>
{posts && posts.length > 0 ? (
<FlatList
data={posts}
renderItem={({ item }) => (
<Post
post={item}
navigation={navigation}
style={globalStyles.list_of_posts}
/>
)}
keyExtractor={(item, index) => index.toString()}
/>
) : (
<Text>Nothing to show here</Text>
)}
<Pressable
title="edit"
onPress={() => {
navigation.navigate("CreatePost", { navigation });
}}
style={globalStyles.plus_btn}
>
<Text style={globalStyles.plus_btn_text}>+</Text>
</Pressable>
</SafeAreaView>
);
};
export default FeedScreen;
As said, I'm new to this so I'd love an explanation of what actually happens and how to do it properly.
I think the prev value of setPosts will always be [] since it does not immediately update if you call it. A standard way to do it is to call setPosts at the end of your function. Can you try this one?
useEffect(() => {
const getPostData = async () => {
const q = collection(db, "posts");
const docSnap = await getDocs(q);
const promises = docSnap.docs.map(async (item) => {
const tmp = collection(db, "posts", item.id, "userPosts");
const tmpSnap = await getDocs(tmp);
return tmpSnap.docs.map((element) => element.data());
});
const arrayOfPosts = await Promise.all(promises);
let newPosts = [];
arrayOfPosts.forEach((posts) => {
newPosts = [...newPosts, ...posts];
});
setPosts(newPosts);
};
getPostData().catch(console.error);
return;
}, []);

React Native Using ref from a hook

I'm trying to optimize my code with hooks. I am thinking to move all bottom sheet refs into a useBottomSheet hook so I can share those refs and be able to manipulate the bottom sheet from any components that import the refs, or callbacks that use those refs. SO I have this:
export const useBottomSheet = () => {
const searchModalRef = useRef<BottomSheetModal>(null);
const handleOpenFilters = useCallback(() => {
console.log('GO');
searchModalRef.current?.snapToIndex(0);
}, []);
In my screen I have
const SearchScreen = () => {
const { searchModalRef } = useBottomSheet();
return (
<>
<Button onPress={() => searchModalRef.current?.snapToIndex(0)} title="PRESS" />
<BottomSheet
ref={searchModalRef}
...
/>
When I press the button, the BottomSheet moves. But when I import const { handleOpenFilters } = useBottomSheet(); in another component and use it, I can see it prints "GO" in the console, but the bottomsheet doesn't move. How come?
It looks like you forgot to return the values you destructure when you call the hook!
export const useBottomSheet = () => {
const searchModalRef = useRef<BottomSheetModal>(null);
const handleOpenFilters = useCallback(() => {
console.log('GO');
return searchModalRef.current?.snapToIndex(0);
}, []);
// add this:
return { searchModalRef, handleOpenFilters }
}

dynamic textInput re-renders the whole component

It is part of a course so library is not an option. Basically, given a json object, generate a form. I can see the elements but I can't type in them. From my understanding, on each typing, the component is being rendered so the useState is being re-initalized. The only way I can type is if i remove the
value={formFields[id]}
from the TextInput.
https://snack.expo.io/#wusile/tenacious-fudge
Here is my code:
/* eslint-disable react/jsx-closing-bracket-location */
import React, { useContext, useState, useEffect } from 'react';
import { View, ScrollView, Text } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
/*
Build a form dynamically from jsonData
see examples/sampleform.json file
*/
const defineFormFields = (data) => {
/*
Define the state to use along with default values.
*/
const stateData = {};
data.forEach((e) => {
stateData[e.id] = e.defaultValue || '';
});
return stateData;
};
const MyComponent = ({ jsonData }) => {
const [formFields, updateFormFields] = useState(defineFormFields(jsonData));
const [currentSegmentElements, updateCurrentViewElements] = useState([]);
const updateFormData = (fieldName, value) => {
const updatedValue = {};
updatedValue[fieldName] = value;
updateFormFields({
...formFields,
...updatedValue
});
};
const elementTypes = {
text(label, id) {
return (
<TextInput
key={id}
accessibilityHint={label}
label={label}
defaultValue={formFields[id]}
value={formFields[id]}
placeholder={label}
onChangeText={(value) => updateFormData(id, value)}
/>
);
}
};
const buildSegment = () => {
/*
Which segment/portion of the json to show
*/
const uiElements = [];
jsonData.forEach((e) => {
const definition = elementTypes[e.type](
e.label,
e.id
);
uiElements.push(definition);
});
updateCurrentViewElements(uiElements);
};
useEffect(() => {
buildSegment();
}, []);
return (
<ScrollView>
<View>
<View>
{currentSegmentElements.map((m) => m)}
</View>
</View>
</ScrollView>
);
};
const FormBuilder = React.memo(MyComponent);
export default FormBuilder;
Now where I need a form, I do:
const jsonData = [
{
"id":"FN",
"label":"FIrst Name",
"type":"text"
},
{
"id":"SN",
"label":"Last Name",
"type":"text"
},
{
"id":"countryCode",
"label":"Country Code",
"defaultValue":"US",
"type":"text"
}
]
<FormBuilder jsonData={jsonData} />
replace your useEffect by this.
useEffect(() => {
buildSegment();
}, [formFields]);

Screen State not Updating from AsyncStorage when going back

I'm building a React Native app.
My app has 5 Screens: Home (initialRouteName), DeckPage, QuestionPage, NewCardPage, NewDeckPage. (in this order)
I'm using Redux for state management. The state is updating from AsyncStorage.
The component that does the fetching is the class component "Home" by dispatching the "fetching" function in componentDidMount.
Component NewCardPage, NewDeckPAge are also updating the state with new content by dispatching the same fetching function as the Home when a button is pressed.
My problem appears when I want to delete a Deck component from inside DeckPage parent component. The function that does this job has this functionality: after removing the item from AsyncStorage, updates the STATE, and moves back to Screen HOME. The issue is that when I go back to HOME component the state doesn't update with the latest info from AsyncStorage.
This is not the case when I'm doing the same operation in the other 2 components NewCardPage, NewDeckPage.
I'll paste the code below:
import React, { Component } from "react";
import { connect } from "react-redux";
import { View, Text, StyleSheet, FlatList } from "react-native";
import Header from "../components/Header";
import AddDeckButton from "../components/AddDeckButton";
import DeckInList from "../components/DeckInList";
import { receiveItemsAction } from "../redux/actions";
class Home extends Component {
componentDidMount() {
this.props.getAsyncStorageContent();
}
renderItem = ({ item }) => {
return <DeckInList {...item} />;
};
render() {
const { items } = this.props;
// console.log(items);
const deckNumber = Object.keys(items).length;
return (
<View style={styles.container}>
<Header />
<View style={styles.decksInfoContainer}>
<View style={styles.deckNumber}>
<View style={{ marginRight: 50 }}>
<Text style={styles.deckNumberText}>{deckNumber} Decks</Text>
</View>
<AddDeckButton />
</View>
<View style={{ flex: 0.9 }}>
<FlatList
data={Object.values(items)}
renderItem={this.renderItem}
keyExtractor={(item) => item.title}
/>
</View>
</View>
</View>
);
}
}
const mapStateToProps = (state) => {
return {
items: state.items,
};
};
const mapDispatchToProps = (dispatch) => {
return {
getAsyncStorageContent: () => dispatch(receiveItemsAction()),
};
};
-----------DECKPAGE COMPONENT------------
import React from "react";
import { View, StyleSheet } from "react-native";
import Deck from "../components/Deck";
import { useSelector, useDispatch } from "react-redux";
import { removeItemAction, receiveItemsAction } from "../redux/actions";
import AsyncStorage from "#react-native-community/async-storage";
const DeckPage = ({ route, navigation }) => {
const { title, date } = route.params;
const questions = useSelector((state) => state.items[title].questions);
const state = useSelector((state) => state.items);
const dispatch = useDispatch();
// const navigation = useNavigation();
const handleRemoveIcon = async () => {
await AsyncStorage.removeItem(title, () => {
dispatch(receiveItemsAction());
navigation.goBack();
});
};
console.log(state);
return (
<View style={styles.deckPageContainer}>
<Deck
handleRemoveIcon={handleRemoveIcon}
title={title}
questions={questions}
date={date}
/>
</View>
);
};
-----------This is my ACTIONS file----------
import AsyncStorage from "#react-native-community/async-storage";
export const RECEIVE_ITEMS = "RECEIVE_ITEMS";
// export const REMOVE_ITEM = "REMOVE_ITEM";
export const receiveItemsAction = () => async (dispatch) => {
const objectValues = {};
try {
const keys = await AsyncStorage.getAllKeys();
if (keys.length !== 0) {
const jsonValue = await AsyncStorage.multiGet(keys);
if (jsonValue != null) {
for (let element of jsonValue) {
objectValues[element[0]] = JSON.parse(element[1]);
}
dispatch({
type: RECEIVE_ITEMS,
payload: objectValues,
});
} else {
return null;
}
}
} catch (e) {
console.log(e);
}
};
-----This is my REDUCERS file----
import { RECEIVE_ITEMS, REMOVE_ITEM } from "./actions";
const initialState = {
};
const items = (state = initialState, action) => {
switch (action.type) {
case RECEIVE_ITEMS:
return {
...state,
...action.payload,
};
// case REMOVE_ITEM:
// return {
// ...state,
// ...action.payload,
// };
default:
return state;
}
}
export default items;
-----This is my UTILS file----
import AsyncStorage from "#react-native-community/async-storage";
export const removeDeckFromAsyncStorage = async (title)=>{
try{
await AsyncStorage.removeItem(title);
}
catch(e){
console.log(`Error trying to remove deck from AsyncStorage ${e}`);
}
}

How to re render react hook function component when redux store change?

I have a function component UpdateCustomerScreen connect with redux store and use react-navigation navigate to SelectorGenderScreen.
selectedCustomer is my redux store data. I change the data on SelectorGenderScreen, when I use navigation.pop() to UpdateCustomerScreen. I have no idea how to re render the UpdateCustomerScreen.
Here is my UpdateCustomerScreen:
const UpdateCustomerScreen = ({ navigation, selectedCustomer }) => {
const gender = changeGenderOption(selectedCustomer.sex); // gender is an array.
const [sex, setSex] = useState(gender); // set array to my state.
console.log('sex', sex);
return (
<View>
<TouchableOpacity onPress={() => navigation.push('SelectorGenderScreen')}
<Text>Navigate to next screen</Text>
</TouchableOpacity>
</View>
);
const mapStateToProps = (state) => {
const { selectedCustomer } = state.CustomerRedux;
return { selectedCustomer };
};
export default connect(mapStateToProps, {})(UpdateCustomerScreen);
Here is my SelectorGenderScreen:
const SelectorGenderScreen = ({ navigation, selectedCustomer, changeGender }) => {
const gender = changeGenderOption(selectedCustomer.sex);
const [genderOption, setGenderOption] = useState(gender);
return (
<Header
title={Translate.chooseStore}
leftComponent={
<BackButton onPress={() => navigation.pop()} />
}
/>
<TouchableOpacity onPress={() => changeGender(selectedCustomer, genderOption)}>
<Text>Change the redux store data</Text>
</TouchableOpacity>
);
const mapStateToProps = (state) => {
const { selectedCustomer } = state.CustomerRedux;
return { selectedCustomer };
};
const mapDispatchToProps = dispatch => {
return {
changeGender: (selectedCustomer, genderOption) => {
dispatch(changeGender(selectedCustomer, genderOption));
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SelectorGenderScreen);
I try to use useCallback() in UpdateCustomerScreen. When I navigation.pop(), It still doesn't re render.
// my state
const [sex, setSex] = useState(gender);
// It is not working
useCallback(() => {
console.log(sex);
},[sex]);
// It is not working
console.log('sex', sex);
return (
// my view
);
Any way to re render the UpdateCustomerScreen when redux store value has been changed ?