Get value from multiple Switch in react native - javascript

I have multiple switch (around 40 to 70) in a component depending on the number of rows fetched from database. I am rendering each switch with every row in a flatlist (every item is assigned with a ID). In the end, I want to submit all the values and store them in database along with id and and it;s respective switch status (true / false).
I want to do it like a form in HTML where we get all the values of form after submitting the form.
This is the component where flatlist is rendered. I have removed unnecessary code because I am able to display the flat list without any error and warning.
const [stData, setStData] = useState([]);
useEffect(()=> {
// Here I am fetching data from server using axios
// setStData(fetchedData);
})
<View>
<FlatList
data={stData}
keyExtractor={(item) => item.registration_id}
renderItem={(stData) => (
<ListItem
name={stData.item.name}
registrationNo={stData.item.registration_id}
data={stData}
isPresent={stData.item.isPresent}
setData={setStData}
/>
)}
/>
This is ListItem component
<View>
<View>
<Text>{props.name}</Text>
<Text>{props.id}</Text>
</View>
<Switch
trackColor={{ true: "red" }}
thumbColor={"white"}
onValueChange={() =>
props.setData(
props.data.map((item) =>
item.registration_id === props.registrationNo
? { ...item, isPresent: !props.isPresent }
: item
)
)
}
value={props.isPresent}
/>
</View>
Update
Now whenever I am trying to toggle the switch button, TypeError: undefined is not a function (near '...props.data.map...') is occured.

While creating const [isPresent, setIsPresent] = useState(false); at child component, you make it a bit rough unnesserally for adding it afterwards to stData, consider store it there from the begging
// dummy data with { isPresent } at main obj
const [data, setData] = useState(stData.map(obj => {...obj, isPresent: false})
<View>
<FlatList
data={data}
keyExtractor={(item) => item.id}
renderItem={({item, id, isPresent}) => (
<ListItem
name={item}
id={id}
data={data}
setData={setData}
isPresent={isPresent}
/>
)}
/>
</View>
// child component
<View>
<View>
<Text>{props.name}</Text>
<Text>{props.id}</Text>
</View>
<Switch
trackColor={{ true: "red" }}
thumbColor={"white"}
onValueChange={() => props.setData(props.data.map(item => item.id == props.id ? { ...item, isPresent: !props.isPresent } : item)}
value={props.isPresent}
/>
</View>
EDIT
when you call renderItem={(stData) =>,
stData in scope of this renderItem isn't stData from state anymore, including at data={stData}
change it to
<FlatList
data={stData}
keyExtractor={(item) => item.registration_id}
renderItem={({item}) => (
<ListItem
name={item.name}
registrationNo={item.registration_id}
data={stData}
isPresent={item.isPresent}
setData={setStData}
/>
)}
/>
now data={stData}gonna evalute correctly, and data.map will be possible action

Related

How to render component via FlatList?

Using react native with typescript and redux toolkit
Hi I'm bothering with render a list of messages via FlatList. By ScrollView everything rendering good but I need to implement infiniti scroll. So I'm doing something like this
const MessagesScreen = () => {
const companyId = useAppSelector(getCompanyId);
const userId = useAppSelector(getUserId);
const {
data: messages,
isLoading,
refetch
} = useGetMessagesQuery({ userId, companyId });
useFocusEffect(refetch);
return (
<FlatList
data={messages}
renderItem={() => {
<Messages messages={messages} />;
}}
/>
);
};
In return() I'm trying to render FlatList with component Messages which is down here:
const Messages = ({ messages }: { messages: Message[] }) => {
const navigation =
useNavigation<RootStackScreenProps<'DrawerNavigator'>['navigation']>();
const { colors } = useTheme();
return (
<View style={styles.container}>
{messages.map(message => {
const createdAt = message.created_at;
const isRead = message.read;
const icon = isRead ? 'email-open-outline' : 'email-outline';
const onClick = () => {
navigation.navigate('Message', {
messageId: message.id
});
};
return (
<TouchableOpacity key={message.id} onPress={onClick}>
<View
style={[styles.message, { borderBottomColor: colors.separator }]}
>
<View style={styles.iconPart}>
<Icon
name={icon}
type="material-community"
style={
isRead
? { color: colors.separator }
: { color: colors.inputFocus }
}
size={24}
></Icon>
</View>
<View style={styles.bodyPart}>
<Text
numberOfLines={1}
style={[isRead ? styles.readSubject : styles.unReadSubject]}
>
{message.subject}
</Text>
<Text
numberOfLines={1}
style={[isRead ? styles.readBody : styles.unReadBody]}
>
{message.body}
</Text>
</View>
<View style={styles.datePart}>
<Text style={{ color: colors.shadow }}>
{dayjs(createdAt).fromNow()}
</Text>
</View>
</View>
</TouchableOpacity>
);
})}
</View>
);
};
Actually behaviour is just rendering white screen with error
Possible Unhandled Promise Rejection (id: 17):
Error: Objects are not valid as a React child (found: object with keys {id, msg_type, created_at, subject, body, author, company_id, read}). If you meant to render a collection of children, use an array instead.
there is problem with your call back function:
you are not returning Messages component
1:Remove curly braces
return (
<FlatList
data={messages}
renderItem={() => <Messages messages={messages}/> }
/>
);
2:Add return statement
return (
<FlatList
data={messages}
renderItem={() => {
return <Messages messages={messages} />;
}}
/>
);
Couple things:
You're using the renderItem callback incorrectly:
<FlatList
data={messages}
renderItem={() => {
// ^ ignoring the renderItem props
return <Messages messages={messages} />;
}}
/>
Here, for each item in the messages array, you're rendering a component and passing all the messages into it. So you'll get repeated elements.
The renderItem callback is passed {item, index} where item is the CURRENT item in the array (index is the index into the array)
See docs here:
https://reactnative.dev/docs/flatlist
The usual thing is the renderItem callback renders ONE item at a time, like this:
<FlatList
data={messages}
renderItem={({item}) => {
return <Message message={item} />;
}}
/>
e.g. I'd make a <Message/> component that renders one item only.

How do I change the state present in a specific item within a flatlist?

I am generating a flatlist that contains comments. Inside the comment component, I'm using a state isCollpsed to determine if the individual comment is collapsed or not. Pressing on each individual comment does make it collapse. However, I want to manipulate this state from the parent component without affecting every other comment. How could I achieve this?
I tried using the reference hook to access each individual item in the flatlist but it keeps returning 'undefined'. I'm using the react-native-collapsible library to collapse the comments.
My Flatlist:
<FlatList
data={SAMPLE_COMMENTS}
keyExtractor={keyExtractor}
renderItem={({item})=>
<Comment
ref={(el) => {rowRefs.current[item.id] = el} }
onPress={()=>{rowRefs.current[item.id].collapseFunction()}}
body={item.body}
author={item.author}
level={item.level}
createdAt={item.createdAt}
commentId={item.id}
commentChildren={item.replies} />}
/>
Comment Component :
const [isCollapsed, setIsCollapsed] = useState(false);
const collapseFunction = () => {setIsCollapsed(!isCollapsed)};
return (
<Collapsible collapsed={isCollapsed}>
<TouchableWithoutFeedback onPress={onPress}>
<View style={styles.container}>
</View>
</TouchableWithoutFeedback>
</Collapsible>
you can use recursive function
// add this to parent
<MapComments
comments={SAMPLE_COMMENTS}
childClickHandler={onItemClickHandler}
/>
// MapComments component
const MapComments= ({
Comments= [],
childClickHandler,
}) => {
return (
<ScrollView>
<Tree
CommentTree={CommentTree}
childClickHandler={childClickHandler}
/>
</ScrollView>
);
};
const Tree = ({CommentTree= [], childClickHandler}) => {
return (
<View>
{CommentTree.map(tree => (
<TreeNode
key={tree.commentId}
node={tree}
childClickHandler={childClickHandler}
/>
))}
</View>
);
};
const TreeNode = ({node, childClickHandler}) => {
const [childVisible, setChildVisiblity] = useState(false);
const hasChild = node.commentChildren.length > 0 ? true : false;
return (
<View
style={{marginRight: node.Level > 1 ? 40 : null}}>
<TouchableOpacity
onPress={() =>
hasChild ? setChildVisiblity(prev => !prev) : childClickHandler(node)
}>
<Text numberOfLines={1} style={styles.label}>
{node.body}
</Text>
{hasChild ? (
<AntDesign name={childVisible ? 'minus' : 'plus'}
/>
) : (
<FontAwesome name="circle" />
)}
</TouchableOpacity>
{hasChild && childVisible && (
<Tree
childClickHandler={childClickHandler}
knowledgeTree={node.commentChildren}
/>
)}
</View>
);
};

Property not being added to object

I have a object which has an array inside it. Each array has multiple objects. So using the .map function I am looping over the array inside the object. Each array item has a click function where I toggle the item. Initial state of the array item is this
{
DisplayText: "Foresatte"
Selectable: true
UserRecipientToInclude: "IncludeGuardianRecipient"
}
When I do this
choice.Selected = false
and console logs the result the newly added item is not present in the object. Why is that?
Here is the code
{c.UserDropdownMenuChoices.map(choice => {
return ( <TouchableHighlight
{...testProperties(choice.DisplayText, true)}
style={{ opacity: !choice.Selectable ? 0.4 : 1 }}
onPress={() => {
this.selectChoice(c.UserDropdownMenuChoices, choice, c)
}}
underlayColor={'transparent'}
key={choice.DisplayText}
>
<View style={styles.choiceContainer}>
{
choice.selected ? (
//<MaterialCommunityIcons name={'checkbox-marked'} style={styles.checkboxClick} size={20} />
<Icon
type={'material-community'}
name={'checkbox-marked'}
iconStyle={styles.checkboxClick}
size={20}
/>
) : (
<Icon
type={'material-community'}
name={'checkbox-blank-outline'}
iconStyle={styles.checkboxDefault}
size={20}
/>
)
//DONE: <MaterialCommunityIcons name={'checkbox-blank-outline'} style={styles.checkboxDefault} size={20} />
}
<Text style={styles.displayText}>{choice.DisplayText}</Text>
</View>
</TouchableHighlight> )}
and my function is like this
selectChoice(choicesList, choice, contact) {
choice.selected = true
...
console.log(choice) // doesn't have the new property
}
This code is for a react native application
I have previously solved a similar issue by simply scoping out the select hook inside the .map without mapping the attribute onto the array itself.
So what I did was:
import MenuRow from "./menu_row"
...
const Rooms = allRooms.map((room, index) => {
return (
<MenuRow key={room.id} room={room}/>
)
})
Inside MenuRow.js
const MenuRow = (props) => {
let room = props.room
const [selected, setSelected] = useState(true) // Checked by default
return (
<TouchableOpacity onPress={() => {setSelected(!selected), applySelected(room.id, selected) }} style={s.checkrow}>
...
{selected ?
// SELECTED
<View style={s.checked}></View>
:
// NOT SELECTED
<View style={s.unchecked}></View>
}
</TouchableOpacity>
)
However you could also give this a try:
https://stackoverflow.com/a/44407980/4451733

Remove an item in AsyncStorage using FlatList

Sorry for the inexperience, but how do I remove an Item in Async Storage renderized in Flat List, for example:
This is my component that creates a flatlist
export default function Saved() {
const [colors, setColors] = useState([]);
useEffect(() => {
async function getStorage() {
const nomeStorage = await AsyncStorage.getAllKeys();
if (nomeStorage != null) {
setColors(nomeStorage);
}
}
getStorage();
}, [colors])
return (
<View style={styles.body}>
<FlatList
data={colors}
keyExtractor={(item) => item}
renderItem={({ item }) => <Saveds data={item} />}
/>
</View>
);
}
and this is my FlatList renderized component
export default function Saveds(props) {
return (
<View>
<View style={styles.Boxes}>
<Box color={props.data}>
<Badge
badgeStyle={styles.badge}
value={<Text style={styles.color}>{props.data}</Text>}
/>
</Box>
<TouchableOpacity style={styles.btn}>
<Icon name={'trash-outline'} color={'#FFF'} size={30} />
</TouchableOpacity>
</View>
</View>
);
}
I need one way to when I click in my TouchableOpacity, I delete the selected data in my AsyncStorage.
The name in my AsyncStorage is the same as the value, so I can delete the AsyncStorage getting the value of my props.data.
Anyone can help me?
Deleting from your async storage should be as easy as just calling AsyncStorage.removeItem(key)
I had some similar functionality in an app that I made a while ago, I attached the delete function call to the onLongPress prop of touchableOpacity:
<TouchableOpacity
onPress={() => navigation.navigate('UserScreen', data)}
onLongPress={handleLongPress}>
<View style={styles.container}>
// ...
</View>
</TouchableOpacity>
And earlier in the component, I defined a function that handles the deleting:
const handleLongPress = async () => {
// In your instance, you should be OK to replace data.key with props.data
await AsyncStorage.removeItem(data.key);
/* I then had another function that was passed in as a prop
to update another component when the deletion had taken place */
await onChange();
};

How to add load more features if my API did not have pagination - react native?

In Home screen, I get data "Songs" from API and save it in the state "Big array".
And I use FlatList to render it, so it rendered fine but I have a too long scroll!
so in data FlatList prop, I slice the array like this
<FlatList
data={songs.slice(0,9)}
...
/>
and it renders 10 songs as expected :D But I want to add Load more when scroll to end
My thought is
add a flag in state like
state={
page: 10
}
<FlatList
data={songs.slice(0,this.state.page)}
onEndReached={this.handleLoadMore}
onEndReachedThreshold={0}
...
/>
handleLoadMore = () => {
this.state.songs.length <= this.state.page ? this.setState({page: this.state.page + 10, loading: true}) : null
};
So have any other thoughts How can I handle this case?
Edit
Full FlatList code snippet
// recent Songs FlatList
_renderItem = ({item, index}) => {
const {recent_songs} = this.state;
return (
<TouchableNativeFeed
key={item.id}
onPress={() => {
this.props.saveSongs(recent_songs, index);
this.props.isPlaying(true);
this.props.isPauseTrigger(!this.props.isPauseTrigger);
}}
background={TouchableNativeFeedback.Ripple('white')}
delayPressIn={0}
useForeground>
<Card style={styles.card} noShadow={true}>
<FastImage
source={{uri: item.img}}
resizeMode={FastImage.resizeMode.cover}
style={styles.cardImg}
/>
<Body style={styles.cardItem}>
<View style={styles.radioCardName}>
<View style={styles.cardViewFlex}>
<Text
lineBreakMode="tail"
ellipsizeMode="tail"
numberOfLines={1}
style={styles.text}>
{item.name}
</Text>
</View>
</View>
</Body>
</Card>
</TouchableNativeFeed>
);
};
{/* Recent Songs Here*/}
<View style={{marginVertical: 10}}>
<FlatList
style={{flex: 1}}
horizontal={true}
showsHorizontalScrollIndicator={false}
data={recent_songs.slice(0, 10)}
contentContainerStyle={{flexGrow: 1}}
ListEmptyComponent={<EmptyList />}
keyExtractor={(track, index) => track.id.toString()}
initialNumToRender={10}
renderItem={this._renderItem}
/>
</View>
something like this with flatlist and local pagination
constructor(props) {
super(props);
this.state = {
...
itemPerPage : 10
currentPage : 1, // we keep a track inside the state on each page we are for pagination
songs:[], // contain the songs used by flatlist to render
allSongs : [ ] // contain all the songs returned by api
}
}
async componentDidMount() {
// get the songs from api
let allSongs = await GetSONGS();
this.setState({ allSongs , songs: allSongs.slice(0,this.state.currentPage*this.state.itemPerPage ) });
}
handleLoadMore = async() => {
this.setState({
songs: [ ...this.state.songs , allSongs.slice(this.state.currentPage*this.state.itemPerPage,(this.state.currentPage+1)*this.state.itemPerPage ) ] , // concat the old and new data together
currentPage : this.state.currentPage +1
})
}
render(){
return(
<FlatList
data={this.state.songs}
keyExtractor={(item, index) => index.toString()}
initialNumToRender={10} // how many item to display first
onEndReachedThreshold={5} // so when you are at 5 pixel from the bottom react run onEndReached function
onEndReached={() => {
this.handleLoadMore();
}}
/>
)
}
anyway i use RecyclerListView in a previous project to render list of 10 000 elements

Categories