I am fetching json from API and then I want to display the component
const [jsonCat, setjsonCat] = useState([]);
useEffect(() => {
refreshCat();
}, []);
const refreshCat = async () => {
try {
console.log("refreshing categories");
setjsonCat([]);
getCat().then((response) => {
setjsonCat(response);
});
} catch (e) {
console.log(e);
}
};
const CarousalLoop = (props) => {
const BANNER_Hs = 1;
if (jsonCat.length == 0) {
return <View></View>;
}
const listItemstest = jsonCat.map((link) => {
console.log(link.name);
<View>
<Text style={{ color: "red" }}>{link.name}</Text>
</View>;
});
return (
<View style={{ height: 220, backgroundColor: "brown" }}>
{listItemstest}
</View>
);
};
And Finally my render component has
{jsonCat.length ? <CarousalLoop /> : <ActivityIndicator />}
When I run this code , Activity indicator is shown until API request is fetched and then json is also received properly , console.log(link.name)
is printing the names correctly but CarousalLoop is displayed without any listitems (just brown view component is shown) .
Either you use return keyword
const listItemstest = jsonCat.map((link) => {
console.log(link.name);
return(
<View>
<Text style={{ color: "red" }}>{link.name}</Text>
</View>
)
});
Or wrap in parenthesis
const listItemstest = jsonCat.map((link) => (
<View>
<Text style={{ color: "red" }}>{link.name}</Text>
</View>;
));
You need to return the list of items to render from listItemstest, like this.
const listItemstest = jsonCat.map((link) => {
console.log(link.name);
return <View>
<Text style={{ color: "red" }}>{link.name}</Text>
</View>;
});
Related
I have a simple react native app with two screens.
First screen is the list, where you see your selected groups, and you can remove them, by clicking on trash icon:
export const Settings: NavioScreen = observer(({ }) => {
...
return (
<View flex bg-bgColor padding-20>
<FlashList
contentInsetAdjustmentBehavior="always"
data={toJS(ui.savedGroups)}
renderItem={({item}) => <ListItem item={item} />}
estimatedItemSize={20}
/>
</View>
);
});
};
const ListItem = ({item}: any) => {
const { ui } = useStores();
return (
<View>
<Text textColor style={{ fontWeight: 'bold', fontSize: 15 }}>{item.name}</Text>
<TouchableOpacity onPress={() => ui.deleteGroup(item)}>
<Icon name={'trash'}/>
</TouchableOpacity>
</View>
);
};
The second screen is also the list, where you can add and remove the subjects from the list:
export const Playground: NavioScreen = observer(() => {
...
const groupsToShow =
ui.search && ui.search.length > 0
? ui.groups.filter((p) =>
p.name.toLowerCase().includes(ui.search.toLowerCase())
)
: ui.groups;
return (
<View >
<FlashList
data={toJS(groupsToShow)}
renderItem={({item}) => <ListItem item={item} />}
/>
</View>
);
});
const ListItem = ({item}: any) => {
const { ui } = useStores();
return (
<View>
<Text textColor style={{ fontWeight: 'bold', fontSize: 15 }}>{item.name}</Text>
<View>
<If
_={ui.isGroupSaved(item)}
_then={
<TouchableOpacity onPress={(e) => {ui.deleteGroup(item)}}>
<AntDesign name="heart" size={20} color={Colors.primary} />
</TouchableOpacity>
}
_else={
<TouchableOpacity onPress={(e) => {ui.addGroup(item)}}>
<AntDesign name="hearto" size={20} color={Colors.primary} />
</TouchableOpacity>
}
/>
</View>
</View>
);
};
And now when I remove the group from the first list, the heart icon do not update on the second list. But it should, because there is an if statement on second list, that checks if the group is saved. And if it is not, the heart should have the name="hearto"
I have tried to use the state instead mobx library but it does not also help.
Here is my store written with mobx:
export class UIStore implements IStore {
savedGroups = [];
constructor() {
makeAutoObservable(this);
makePersistable(this, {
name: UIStore.name,
properties: ['savedGroups'],
});
}
addGroup = (group: any) => {
if (true === this.isGroupSaved(group)) {
return;
}
this.savedGroups.push(group);
}
isGroupSaved = (group: any) => {
return -1 !== this.savedGroups.findIndex(g => g.id === group.id);
}
deleteGroup = (groupToDelete: any) => {
this.savedGroups = this.savedGroups.filter((group) => group.id !== groupToDelete.id);
}
}
I have an array of conversations and a function that checks if the recipient is online. However when that function changes its return value (boolean), the flatlist does NOT rerender. I tried extraData but with no luck. My code is:
flatList
<FlatList
data={conversations}
extraData={isRefreshing}
renderItem={(conversation) => (
<TouchableOpacity
onPress={() => selectConversation(conversation.item)}
style={{
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
borderBottomWidth: 1,
padding: 5,
marginBottom: 5,
}}
>
<View>
<Text>{getRecipient(conversation.item).displayName}</Text>
<Text>{conversation.item.latestMessage}</Text>
</View>
{isUserOnline(conversation.item) && (
<Text style={{ color: "green" }}>ONLINE</Text>
)}
</TouchableOpacity>
)}
keyExtractor={(item) => item._id}
/>
useEffect
useEffect(() => {
let handler = (data) => {
console.log(data);
setOnlineUsers((prevState) => {
return data;
});
setRefreshing(!isRefreshing);
};
const unsubscribe = navigation.addListener("focus", () => {
console.log("focused");
socket.on("online-users-data", handler);
socket.emit("join-online-users");
getConversations();
});
return () => {
socket.emit("leave-online-users");
socket.off("online-users-data", handler);
unsubscribe();
};
}, []);
isUserOnline()
function isUserOnline(conversation) {
const user = getRecipient(conversation);
const onlineUser = onlineUsers.find((u) => u.userId === user._id);
return (
user && onlineUser && user._id.toString() === onlineUser.userId.toString()
);
}
I have solved this by adding onlineUsers to extraData. Damn it was confusing.
I am using flat list to display data which is coming from unsplash api. But here it keeps on complaining to saying this
Invariant Violation: Text strings must be rendered within a component
I am not even using any text component. I have no idea what is wrong here.
App.js
export default function App() {
const [loading, setLoading] = useState(true);
const [image, setImage] = useState([]);
const {height, width} = Dimensions.get('window');
const URL = `https://api.unsplash.com/photos/random?count=30&client_id=${ACCESS_KEY}`;
useEffect(() => {
loadWallpapers();
}, [])
const loadWallpapers =() => {
axios.get(URL)
.then((res) => {
setImage(res.data);
setLoading(false);
}).catch((err) => {
console.log(err)
}).finally(() => {
console.log('request completed')
})
}
const renderItem = (image) => {
console.log('renderItem', image);
return (
<View style={{height, width}}>
<Image
style={{flex: 1, height: null, width: null}}
source={{uri : image.urls.regular}}/>
</View>
)
}
return loading ? (
<View style={{flex: 1, backgroundColor: 'black', justifyContent: 'center',alignItems: 'center'}}>
<ActivityIndicator size={'large'} color="grey"/>
</View>
): (
<SafeAreaView style={{flex: 1, backgroundColor: 'black'}}>
<FlatList
horizontal
pagingEnabled
data={image}
renderItem={({ item }) => renderItem(item)} />}
/>
</SafeAreaView>
)
}
I thing data of Flatlist is null, try
<FlatList
horizontal
pagingEnabled
data = {image ? image : []}
renderItem={({ item }) => renderItem(item)} />}
/>
I needed to do something like this to make it work.
const renderItem = ({ item }) => { <---- I have destructured item here
console.log(item)
return (
<View style={{ flex: 1 }}>
</View>
);
};
<FlatList
scrollEnabled={!focused}
horizontal
pagingEnabled
data={image}
renderItem={renderItem}
/>
I have connect socket successfully and getting proper response also from socket connection. State is updating successfully but issue is data is not updating in screen (renderTabSection not render updated data).
class Test extends Component{
constructor (props) {
super(props);
this.animatedValue = new Animated.Value(0);
}
componentDidMount(){
const { restaurantId } = this.props;
this.socket = new WebSocket('wss://test.com/' + id);
this.socket.onopen = (data) =>{
console.log('Socket connected');
}
this.socket.onmessage = (e) => {
this.props.socketData(e.data);
//this.socketUpdate();
};
this.socket.onclose = () => {
this.socket = new WebSocket('wss://test.com/' + id);
}
}
componentWillMount(){
this.props.resetVenueDetails();
this.props.showLoader();
}
componentWillReceiveProps(nextProps){
this.renderTabSection();
}
componentWillUnmount() {
this.socket.close();
}
onTabClick(tabId){
this.props.onTabChange(tabId);
}
renderTabSection(){
let playlist = this.props.playlists;
const {
container,
tabHeaderStyle,
tabHeadStyle,
tabDetailBox,
albumTextStyle,
selectedTabStyle,
hideTabContentStyle
} = styles;
return (
<View style={{flex:1, borderBottomColor: '#000', borderBottomWidth: 2 }}>
<View style={{flex:0,flexDirection:'row'}}>
<View style={tabHeadStyle}>
<TouchableOpacity onPress={this.onTabClick.bind(this,1)}>
<Text style={ [tabHeaderStyle, this.props.tabSelected == 1 ? selectedTabStyle : '' ] }>
Playlist
</Text>
</TouchableOpacity>
</View>
</View>
<View style={[container, this.props.tabSelected == 1 ? "" : hideTabContentStyle]} >
<ScrollView horizontal={true}>
<View style={{ flex: 1,flexDirection: 'row' }}>
{ this.renderPlaylistAlbums('user', playlist) }
</View>
</ScrollView>
</View>
</View>
);
}
renderPlaylistAlbums(type, playlist){
let songsArray = [];
const { tabDetailBox, albumTextStyle } = styles;
playlist = playlist.length > 0 ? playlist : PLAYLIST_SECTION;
playlist.filter( (data, i) => {
if( data.type == type ){
if(data.songs.length > 0 ){
let image = data.songs[0] && data.songs[data.songs.length -1].imageUrl ?
{ uri : data.songs[data.songs.length -1].imageUrl } :
require('../assets/images/playlist.png');
let imageStyle = data.songs[0] && data.songs[data.songs.length -1].imageUrl ?
{ width: '70%',height:'60%', borderRadius: 10 } :
{ width: '60%',height:'60%' };
songsArray.push(
<TouchableOpacity key={i}>
<View style={ tabDetailBox }>
<Image
source={ image }
style={ imageStyle } />
<Text style={ albumTextStyle }>{ data.name }</Text>
</View>
</TouchableOpacity>
);
}
}
});
return songsArray;
}
loadSpinner(){
if( this.props.loading ){
return ( <View style={{ flex:1, position:'absolute', width:'100%' }} ><Spinner /></View> );
}
}
render(){
const { backgroundImage } = styles;
return (
<View style={{ flex: 1 }}>
<ImageBackground source={APP_BACKGROUND_IMAGE.source} style={backgroundImage}>
{ this.loadSpinner() }
<View style={{ flex:1, backgroundColor:'rgba(0,0,0,.7)' }}>
{ this.renderTabSection() }
</View>
</ImageBackground>
<Footer headerText='Home' />
</View>
);
}
}
const mapStateToProps = state => {
return {
error:state.home.error,
loading:state.home.loading,
tabSelected:state.restaurantDetail.tabSelected,
playlists: state.restaurantDetail.playlists
}
}
export default connect(mapStateToProps, { onTabChange, socketData, showLoader, resetVenueDetails })(Test)
I have connect socket successfully and getting proper response also from socket connection. State is updating successfully but issue is data is not updating in screen (renderTabSection not render updated data).
I think you are not setting any state because setState will cause the component to re-render, this is how you can setState
constructor(props){
this.state = {
dataUpdated: false,
anyUseFullVariable: '',
}
}
you can setState when you get response from sockets like this
this.setState({dataUpdated: true})
then you can use the state within render component like this
this.state.dataUpdated
this will re-render the component. This is just an example try doing something similar.
Update
You can also use componentWillRecieveProps, this callback function is triggered whenever there is some change in props
componentWillRecieveProps(nextProps){
if(!isFetching && this.props.data !== nextProps.data) // or implement your preferred condition
this.setState({UpdateList: this.props.data}) // this would call the render function
}
}
i'm trying to declare an variable inside the FlatList component in React Native
But i get unexpected token, when i do declare it.
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => (
let fixture = item.name //unexpected token
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
)
}
/>
</ScrollView>
)
here is my full FixturesScreen cdoe
import React from 'react'
import { View, Text, FlatList, ScrollView, StyleSheet } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import clubData from '../../clubData'
const styles = StyleSheet.create({
container: {
backgroundColor: '#4BABF4',
},
itemTitle: {
color: 'black',
fontSize: 20,
marginTop: 20,
marginBottom: 10,
marginLeft: 15,
},
listItem: {
color: '#FFFFFF',
fontSize: 18,
textAlign: 'center',
marginRight: 15,
marginLeft: 15,
backgroundColor: '#77BEF5',
width: 120,
paddingVertical: 10,
},
})
const CURRENTTGAMEWEEK = 30
const i = CURRENTTGAMEWEEK
const nxt1 = i + 1
const nxt2 = nxt1 + 2
const nxt3 = nxt2 + 1
const nxt4 = nxt3 + 1
const nxt5 = nxt4 + 1
// let fixture
// const team = clubData.data.clubs[0].name
// const hTeam = clubData.data.clubs[0].fixtures[0].homeTeam
// const hTeamShort = clubData.data.clubs[0].fixtures[0].homeTeamShort
// const aTeamShort = clubData.data.clubs[0].fixtures[0].awayTeamShort
//
// if (team === hTeam) // working
// fixture = aTeamShort
// else
// fixture = hTeamShort
console.log(`Now is playing ${fixture}`)
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => (
let fixture = item.name
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
)
}
/>
</ScrollView>
)
FixturesScreen.navigationOptions = {
tabBarTestIDProps: {
testID: 'TEST_ID_HOME',
accessibilityLabel: 'TEST_ID_HOME_ACLBL',
},
tabBarLabel: 'Main',
tabBarIcon: ({ tintColor, focused }) => (
<Ionicons
name={focused ? 'ios-home' : 'ios-home-outline'}
size={26}
style={{ color: tintColor }}
/>
),
}
export default FixturesScreen
So basically what i'm trying to do is declare homeTeam, awayTeam and Fixture inside the flatlist, so i can do an if/else conditional rendering inside the flatlist. I can achieve that outside the flatlist component but it is not right, because i can not compare all objects at once.
While using arrow functions () => ('someValue') is a shortcut for () => { return 'someValue'}.
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: (param1, param2, …, paramN) => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// A function with no parameters should be written with a pair of parentheses.
() => { statements }
// Parenthesize the body of function to return an object literal expression:
params => ({foo: bar})
So if you want to run some code before returning a value you should do like below;
const FixturesScreen = ({ navigation }) => (
<ScrollView style={styles.container}>
<FlatList
data={clubData.data.clubs}
renderItem={({ item }) => { //change to curly braces
let fixture = item.name;
// do something here
return (
<View>
<View>
<Text style={styles.itemTitle}>{item.name}</Text>
<ScrollView horizontal>
<Text style={styles.listItem}>{fixture}</Text>
</ScrollView>
</View>
</View>
);
}}
/>
</ScrollView>
)