How to send data in previous screen with help of goBack()? - react-native

How to send data in previous screen with help of goBack() ?
I tried already. For ex: this.props.navigation.navigate('Login', {name: this.state.name})

If you simply want to pass data to the previous screen then the below works:
Parent screen:
const Parent = () => {
const [data, setData] = useState("");
let navigation = useNavigation();
const onPress = () => {
navigation.navigate('Second', { getData: (x)=>setData(x) }); //<---here you have to pass callback function
};
return (
<View style={{ flex: 1 }}>
<Button
onPress={onPress}
title="Add title here"
color="#841584"
disabled={false}
/>
<Text>{data}</Text>
</View>
);
};
Child screen:
const Child = ({ route }) => { //<------here need to take route
let navigation = useNavigation();
const onPress = () => {
let data = "John";
route.params.getData(data); //<-----this way to update.
navigation.goBack();
};
return (
<View style={{ flex: 1 }}>
<Button
onPress={onPress}
title="Add title here"
color="#841584"
disabled={false}
/>
</View>
);
};

Related

React Native call function outside of App. Flatlist access onPress function

There is example https://reactnative.dev/docs/flatlist
Let's say I want to add button in each flatlist item. All happens inside App.js
const Item = ({ item,.....}) => (
<TouchableOpacity onPress={onPress} style={..}>
<Button title='Go' onPress={() => myFunc('abc')} /> </TouchableOpacity>);
const App = () => {
function myFunc(x){
}
}
I get " ReferenceError: Can't find variable: myFunc "
I solved this by moving Item inside of const App = () => { but I think it might be wrong.
Tell me please, what is the correct way?
You could do something like this:
const App = () => {
const myFunc = (args) => {
// perform your action here.
}
return (
<FlatList
data={[{ title: 'Title Text', key: 'item1' }]}
renderItem={({ item, index, separators }) => (
<TouchableOpacity
key={item.key}
onPress={() => myFunc('abc')}
>
<View style={{ backgroundColor: 'white' }}>
<Text>{item.title}</Text>
</View>
</TouchableOpacity>
)}
/>
)
}
export default App;
Also you do not need to using TouchableOpacity if you are using Button Component already.
And since you are using separate component to render item for FlatList so it can be done as below:
// Considering App as Parent Component
const App = () => {
// Considering Item as separate Component
const Item = ({item, index, separators}) => {
return (
<TouchableOpacity
key={item.key}
onPress={() => myFunc('abc')}
>
<View style={{ backgroundColor: 'white' }}>
<Text>{item.title}</Text>
</View>
</TouchableOpacity>
)
}
const myFunc = (args) => {
// perform your action here.
}
return (
<FlatList
data={[{ title: 'Title Text', key: 'item1' }]}
renderItem={Item}
/>
)
}
export default App;
All code are inside App Component;

Why my virtualized list does not re-render when the data passed as prop actualizes?

I am having a problem that I can't solve by my own. I am making an app for making lists in React Native, and in my main screen, that shows the session initiated by the user, I have to render all the lists that he had saved previously. Here is the code of my session component.
export default function Session({navigation,route}){
const {user} = useContext(myContext)
const [modalVisible, setModalVisible] = useState(false)
const [lists, setLists] = useState(route.params.lists)
let keyListCounter = 0
const handleButton = async () => {
await AsyncStorage.removeItem("token")
navigation.navigate("Login")
}
const updateList = (title,newElement) => {
axios.put(`http://${REACT_APP_BACK_URI}/api/lists/add-list-element`, {nickname: user,title,element: newElement})
.then(res => {
if (res.status == 200) {
setLists(res.data.userLists)
}
})
.catch(err => console.log(err))
}
useEffect(() => {
navigation.setOptions({
title: user,
headerTitleAlign: "left",
headerRight: () => (
<TouchableWithoutFeedback onPress={() => handleButton()}>
<Text style={styles.logoutText}>Logout</Text>
</TouchableWithoutFeedback>
)
})
},[navigation,user])
return (
<View style={styles.mainContainerView}>
<ScrollView style={styles.mainContainerScrollView}>
<View style={styles.textListContainer}>
<Text style={styles.listsText}>LISTAS ACTIVAS: </Text>
<Text style={styles.numberListsText}>{lists.length}</Text>
</View>
{lists.map(elem => <List key={keyListCounter++} list={elem} updateList={updateList}/>)}
</ScrollView>
<Pressable style={styles.newListPressable} onPressIn={() => setModalVisible(true)}>
<Text style={styles.newListText}>+</Text>
</Pressable>
<View style={styles.centeredView}>
<Modal
visible={modalVisible}
animationType="slide"
transparent={true}
>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text>MODAL</Text>
</View>
</View>
</Modal>
</View>
</View>
)
}
My question is why after I actualize the state of "lists", whose elements are passed as props to the List component, the virtualized list that I have in the List component does not re-renderizes automaticaly.
Here I show also the code of the List component.
export default function List({list,updateList}){
const {elements, title} = list
let elementId = 0
const virtualizedList = useRef()
const [showVirtualizedList, setShowVirtualizedList] = useState("none")
const [showDownArrow, setShowDownArrow] = useState(true)
const [showUpArrow, setShowUpArrow] = useState(false)
let [newElementArray, setNewElementArray] = useState([])
let [listElements, setListElements] = useState(elements)
const getItem = (item) => ({
id: elementId++,
title: item
});
//List Pressable Events
const handlePressIn = () => {
if (showVirtualizedList == "none") setShowVirtualizedList("flex")
else setShowVirtualizedList("none")
setShowDownArrow(!showDownArrow)
setShowUpArrow(!showUpArrow)
}
//New element Pressable Events
const handleNewElement = () => {
setNewElementArray([...newElementArray,uuid.v4()])
}
//NewListItem TouchableWithoutFeedback Events
const deleteElementInput = newItemID => {
const elementsArray = newElementArray.filter(elem => elem != newItemID)
setNewElementArray(elementsArray)
}
const addListElement = (newElement,newItemID) => {
updateList(title,newElement)
deleteElementInput(newItemID)
}
useEffect(() => {
virtualizedList.current.setNativeProps({display: showVirtualizedList})
LogBox.ignoreLogs(['VirtualizedLists should never be nested']);
},[showVirtualizedList, virtualizedList])
return (
<ScrollView style={styles.mainContainer}>
<Pressable
style={styles.listElement}
onPressIn={() => handlePressIn()}
>
<View style={styles.titleContainer}>
<Text style={styles.listElementText}>{title} </Text>
<Text style={styles.listElementQuantity}>({listElements.length})</Text>
</View>
<View>
<DownArrow show={showDownArrow}/>
<UpArrow show={showUpArrow}/>
</View>
</Pressable>
<View>
<VirtualizedList
data={listElements}
initialNumToRender={10}
getItemCount={() => listElements.length}
renderItem={({item}) => <ListItem item={item}/>}
getItem={() => getItem(listElements[elementId])}
ref={virtualizedList}
/>
</View>
{newElementArray.length > 0 ? newElementArray.map(elem => {
return (
<NewListItem
key={elem}
id={elem}
newElementArray={newElementArray}
deleteElementInput={deleteElementInput}
addListElement={addListElement}
/>
)
}) : ""
}
<Pressable style={styles.newElementPressable} onPressIn={() => handleNewElement()}>
<Text style={styles.newElementText}>+</Text>
</Pressable>
</ScrollView>
)
}
UPDATE: I solve the problem using a FlatList instead of a VirtualizedList. For some reason the FlatList re-renders when the Item is updated and the VirtualizedList no. I don't know why.....

you need to specify name or key when calling navigate with an object as the argument

i'm having an messages screen and i need to navigate to a "single message" when tapping to the List item of messages but i get this error "you need to specify name or key when calling navigate with an object as the argument"
i have created the "single message" screen and added it as a <Stack.Screen/> also but i don't know what i'm doing wrong.
below is my code:
function MessagesScreen({navigation}) {
const [messages, setMessages] = useState([]);
const [refreshing, setRefreshing] = useState(false);
const loadMessages = async () => {
const response = await messagesApi.getMessages();
setMessages(response.data);
}
useEffect(() => {
loadMessages();
}, []);
const handleDelete = message => {
setMessages(messages.filter((m) => m.id !== message.id));
}
return (
<Screen>
<FlatList
data={messages}
keyExtractor={message => message.id.toString()}
renderItem={({ item }) =>
<ListItem
title={item.fromUserId}
subTitle={item.content}
image={item.image}
onPress={() => navigation.navigate(routes.MESSAGE_SINGLE, item)}
renderRightActions={() =>
<ListItemDeleteAction onPress={() => handleDelete(item)} />}
/>
}
ItemSeparatorComponent={ListItemSeparator}
refreshing={refreshing}
onRefresh={() => {
setMessages([
{
id: 1,
title: 'T1',
description: 'D1',
image: require('../assets/mosh.jpg')
},
])
//setMessages(loadMessages());
}}
/>
</Screen>
);
}
const styles = StyleSheet.create({
})
export default MessagesScreen;
when i'm logging the "onPress" event on the console like this:
onPress={() => console.log('message selected', item)}
heres what i get:
and below is the MessageSingle screen i created to render the message but i dont know how to do it.
function MessageSingle() {
return (
<Screen>
<View style={styles.container}>
<AppText>{"kjhkjhjk"}</AppText>
{/* <AppText>{getMessagesApi}</AppText> */}
</View>
</Screen>
);
}
const styles = StyleSheet.create({
container: {}
});
export default MessageSingle;
so i want to get the message from the list of the messages. maybe i dont have to create e separate screen? i'm a beginner on this
any help would be appreciated!
you need to first add your MessageSingle component to the navigation container. Just put it as one of the screens along your MessagesScreencomponent. Then you need to navigate to it using that name:
onPress={() => navigation.navigate('MessageSingle', {item})}
the above will navigate to the screen with name MessageSingle, and passing the object item as a param.
in order to access this in your MessageSingle component, you need to use the route props.
function MessageSingle({route}) {
console.log('item = ', route.params?.item); // this would be your item.
return (
<Screen>
<View style={styles.container}>
<AppText>{"kjhkjhjk"}</AppText>
{/* <AppText>{getMessagesApi}</AppText> */}
</View>
</Screen>
);
}

Adding Search Bar into Flatlist using Hook, Undefined

i try to create flatlist inside modal with search bar functionality that can filter the result based on user input in the search bar.
For the flatlist everything show up accordingly,
problem i can't filter the data,
i try using .filter from the original full data (list) but result is always undefined is not a data.
Btw data is populate from local .json file to state using useEffect.
Here is the local country.json data :
[
"Japan",
"Korea",
"Thailand",
"Indonesia" ]
Here is part of the source code :
import dataCountry from '../../assets/json/country.json';
const NameScreen = ({ navigation }) => {
// hook
const [list, setList] = useState([]);
const [modalBirthplace, setModalBirthplace] = useState(false);
const [searchText, setSearchText] = useState('');
useEffect(() => {
setList({ dataCountry });
console.log('check List : ', list);
}, [])
const renderItem = ({ item }) => (
<Item title={item.title} />
);
const ListItem = ({ title }) => (
<View>
<TouchableOpacity onPress={() => console.log("ok")}>
<Text style={styles.cityList}>{title}</Text>
</TouchableOpacity>
</View>
);
const searchFilterFunction = searchText => {
setSearchText(searchText);
console.log(searchText)
const newData = list.filter((item) => { // error trigger from this list.filter undefined is not a function
const itemData = item.toUpperCase();
const textData = searchText.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setList(newData);
};
return (
<View style={styles.container}>
<Modal
animationType="slide"
transparent={true}
visible={modalBirthplace}
onRequestClose={() => {
Alert.alert('Modal has been closed.');
}}>
<View style={styles.centeredView}>
<View style={styles.modalView}>
<Text style={styles.modalText}>Choose your country location :</Text>
<TextInput
placeholder="Try japan maybe?"
onChangeText={searchText => searchFilterFunction(searchText)}
value={searchText}
/>
<FlatList
data={list.dataCountry}
renderItem={({ item }) => (
<ListItem
title={item}
/>
)}
keyExtractor={item => item}
/>
<TouchableHighlight
style={{ ...styles.openButton, backgroundColor: '#E15C72' }}
onPress={() => {
setModalBirthplace(!modalBirthplace);
}}>
<Text style={styles.textStyle}>Close Selection</Text>
</TouchableHighlight>
</View>
</View>
</Modal>
</View>
)
}
Anybody know why i can't filter the state?
Thanks a lot before
the problem is your state is an JSON object, not an array:
setList({ dataCountry });
// so list is:
{
dataCountry: [
...
]
}
so, you need to change here
const newData = list.dataCountry.filter((item) => { // here
const itemData = item.toUpperCase();
const textData = searchText.toUpperCase();
return itemData.indexOf(textData) > -1;
});
setList({dataCountry: newData}); // and here
maybe your json like this,
const list = {
dataCountry : [
'UK',
'US'
]
}
List is an object you can't use the filter with an object.
Instead of using array placeholder you can use spread operator like this,
const newData = [...list.dataCountry].filter((item) => {
const itemData = item.toUpperCase();
const textData = searchText.toUpperCase();
return itemData.indexOf(textData) > -1;
});

React Native Function Component ASYNC / AWAIT Problem

sorry for bad English.
My function component not waiting API Function, I'm write async and await and not working again..
"Object are not valid as a React child" error screen...
Please help me :'/
const NormalCarousel = async (props) => {
const navigation = useNavigation();
const [ResponseData, setResponseData] = useState('');
const ComponentAPI = props.api;
const API = await axios.get(ComponentAPI).catch((error) => {alert(error)});
await setResponseData(API);
return(
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
{
ResponseData.map(item => (
<TouchableOpacity style={styles.CarouselTouchable} onPress={() => navigation.navigate("Ürün", {id: item.item_id})}>
<Image
style={styles.CarouselImage}
source={{uri: item?.item_avatar}}
/>
<View style={styles.CarouselView}>
<Text style={styles.CarouselTitle}>{item?.item_name}</Text>
<Text style={styles.CarouselSubtitle}>{item?.item_stock_code}</Text>
</View>
</TouchableOpacity>
))
}
</ScrollView>
)
}
The error is happening because the parent component trying to render this component is actually rendering a Promise which resolves into a component. That's not possible.
You should instead call the function to load the data once on component mount (useEffect). You'll also need to replace useState('') with useState([]) since you're trying to map over this data when rendering.
const NormalCarousel = (props) => {
const { api } = props;
const navigation = useNavigation();
const [responseData, setResponseData] = useState([]);
useEffect(() => {
getAPI();
}, []);
async function getAPI() {
const API = await axios.get(api).catch((error) => alert(error));
setResponseData(API);
}
return(
<ScrollView horizontal showsHorizontalScrollIndicator={false}>
{
responseData.map(item => (
<TouchableOpacity style={styles.CarouselTouchable} onPress={() => navigation.navigate("Ürün", {id: item.item_id})}>
<Image
style={styles.CarouselImage}
source={{uri: item.item_avatar}}
/>
<View style={styles.CarouselView}>
<Text style={styles.CarouselTitle}>{item.item_name}</Text>
<Text style={styles.CarouselSubtitle}>{item.item_stock_code}</Text>
</View>
</TouchableOpacity>
))
}
</ScrollView>
)
}