I am trying to use ListView on my js page and I am getting no data on my screen. The screen is totally blank. Below is the image of the empty screen. I am getting a warning.
Below is my code where I am calling the ListView:
import React, { Component } from 'react';
import { Text, View, StyleSheet, ListView } from 'react-native';
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux'
import reducers from '../reducers/ServiceReducer';
import ServiceItem from './ServiceItem';
const styles = StyleSheet.create({
container: {
flex: 1,
width: 353,
flexWrap: 'wrap',
paddingTop: 20,
paddingLeft: 20,
},
});
const store = createStore(reducers);
class AutoCompActivity extends Component {
componentWillMount() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.dataSource = ds.cloneWithRows(this.props.services);
}
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<ListView
enableEmptySections={true}
dataSource={this.dataSource}
renderRow={(rowData) =>
<ServiceItem services={rowData} />
}
/>
</View>
</Provider>
);
}
}
const mapStateToProps = state => {
return { services: state.services };
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);
const app1 = () => (
<Provider store={store}>
<ConnectedAutoCompActivity />
</Provider>
)
export default app1;
My ServiceItem.js file is below:
import React from 'react';
import { StyleSheet, Text, View, Button, ImagePropertiesAndroid } from 'react-native';
import {connect} from 'react-redux';
import { getTheme } from 'react-native-material-kit';
import Icon from 'react-native-vector-icons/EvilIcons';
import * as actions from '../actions';
const theme = getTheme();
const styles = StyleSheet.create({
card: {
marginTop: 20,
},
title: {
top: 20,
left: 80,
fontSize: 24,
},
image: {
height: 100,
},
action: {
backgroundColor: 'black',
color: 'white',
},
icon: {
position: 'absolute',
top: 15,
left: 0,
color: 'white',
backgroundColor: 'rgba(255,255,255,0)',
},
});
const ServiceItem=(props)=>{
return(
<View>
<Text style={[theme.cardTitleStyle, styles.title]}>{props.services.services}</Text>
</View>
)
}
export default connect(null, actions)(ServiceItem);
My Json file is very simple:
[
{
"services": "Test1"
},
{
"services": "Test2"
},
{
"services": "Test3"
},
{
"services": "Test4"
},
{
"services": "Test4"
}
]
My service.Reducer has the following code:
import services from './services.json';
const initialState = {
services
};
export default (state = initialState, action) => {
switch (action.type) {
default:
return state;
}
}
I checked my code several times and could not find any issue. I also installed react redux. Store is defined as const in my code. I am just trying to show each service as
test1,
test2 on my phone
Any help will be greatly appreciated.
The problem here is that you are using Provider inside connected component.
The connected component should be wrapped inside <Provider>. Replace your code with the following and it will work as expected.
import React, { Component } from 'react';
import { Text, View, StyleSheet, ListView } from 'react-native';
import { Provider, connect } from 'react-redux';
import { createStore } from 'redux'
import reducers from '../reducers/ServiceReducer';
import ServiceItem from './ServiceItem';
const styles = StyleSheet.create({
container: {
flex: 1,
width: 353,
flexWrap: 'wrap',
paddingTop: 20,
paddingLeft: 20,
},
});
const store = createStore(reducers);
class AutoCompActivity extends Component {
componentWillMount() {
const ds = new ListView.DataSource({
rowHasChanged: (r1, r2) => r1 !== r2,
});
this.dataSource = ds.cloneWithRows(this.props.services);
}
render() {
return (
<Provider store={store}>
<View style={styles.container}>
<ListView
enableEmptySections={true}
dataSource={this.dataSource}
renderRow={(rowData) =>
<ServiceItem services={rowData} />
}
/>
</View>
</Provider>
);
}
}
const mapStateToProps = state => {
return { services: state.services };
};
const ConnectedAutoCompActivity = connect(mapStateToProps)(AutoCompActivity);
const App = () => (
<Provider store={store}>
<ConnectedAutoCompActivity />
</Provider>
)
export default App;
Related
To put in context I am building an app as an exercise in a course to program in react native and we are learning Redux
For me everything is fine but I have doubts in two parts in the index of the scene where the application is seen in this case welcome / index.js there is a line that is for 'useSelector' and another is in the reduce of recipe that if the data is well linked because it throws me an error.
"ERROR TypeError: undefined is not an object (evaluating 'store.getState')"
I share the different components of the redux.
Everything is in a store folder and everything is modulated
store/reduce
store/reduce/index.js
import { combineReducers, createStore } from "redux";
import { recipesReducer } from "./reducer";
const rootReducer = combineReducers({
recipes: recipesReducer
});
export default createStore(rootReducer);
store/reducer/recipes.reducer.js
import {recipeTypes} from '../types';
import {recipes} from '../../data';
const { SELECT_RECIPE } = recipeTypes;
const initialState = {
recipes: recipes,
selectedRecipe: null
}
const recipesReducer = (state = initialState, action) => {
switch(action.type) {
case SELECT_RECIPE:
const indexRecipe = state.recipes.findIndex(
(recipe) => recipe.id === action.recipeId
);
if(indexRecipe === -1) return state;
return {
...state,
selectedRecipe: state.recipes[indexRecipe]
}
default:
return state;
}
}
export default recipesReducer;
store/reduce/index.js
export {default as recipesReducer} from './recipes.reducer';
store/types/index.js
export * from './recipes.types';
store/types/recipes.type.js
export const recipeTypes = {
SELECT_RECIPE: 'SELECT_RECIPE',
}
store/action/recipes.action.js
import { recipeTypes } from '../types';
const { SELECT_RECIPE } = recipeTypes;
export const selectRecipe = (id) => {
return {
type: SELECT_RECIPE,
recipeId: id,
};
}
store/action/index.js
export * from './repice.action';
welcome/index
import {Button, CardsRecipes, MenuAlt, Pickers, TT} from '../../components';
import { FlatList, StyleSheet, Text, View } from 'react-native';
import React, { useState } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import Color from '../../constants/colors';
import { recipe } from '../../data';
import { selectRecipe } from '../../store/action';
const Welcome= ({navigation, route}) => {
const dispatch = useDispatch();
const recipe = useSelector(state => state.recipe.recipe);
const onSelected = (item) => {
dispatch(selectRecipe(item.id));
navigation.navigate('Recipe');
}
const renderItem = ({item}) => <CardsRecipes item={item} onSelected={onSelected(item)} />
return (
<View style={styles.container}>
<MenuAlt title = {'Recetas'} />
<View style={styles.textContainer}>
<Text style= {styles.text}>Bienvenido a la App de Recetas de Cocina</Text>
</View>
<View style = {styles.buttonContainer}>
</View>
<FlatList
data= {recipe}
renderItem = {renderItem}
keyExtractor = {item => item.id}
/>
</View >
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.primary,
color: Color.letter,
fontFamily: 'Lato-Regular',
},
textContainer: {
alignItems: 'center',
justifyContent: 'center',
},
text: {
color: Color.letter,
fontSize: 20,
fontWeight: 'bold',
marginTop: 10,
marginBottom: 10,
},
buttonContainer: {
width: '100%',
alignItems: 'center',
marginTop: 10,
marginBottom: 10,
height: 33,
},
});
export default Welcome;
app.js
import {ActivityIndicator, StyleSheet, View} from 'react-native';
import React, { useState } from 'react';
import AppNavigator from './navigation';
import Color from './constants/colors';
import { Provider } from 'react-redux';
import { StatusBar } from 'expo-status-bar';
import { store } from './store';
import { useFonts } from 'expo-font';
export default function App() {
//useState
const [selected, setSelected] = useState(false);
const [order, setOrder] = useState([]);
//funciones
const [loaded] = useFonts({
'Lato-Regular': require('./assets/fonts/Lato-Regular.ttf'),
'Lato-Bold': require('./assets/fonts/Lato-Bold.ttf'),
'Lato-Light': require('./assets/fonts/Lato-Light.ttf'),
'Lato-Italic': require('./assets/fonts/Lato-Italic.ttf'),
'Lato-Black': require('./assets/fonts/Lato-Black.ttf'),
});
if(!loaded) {
return (
<View style={styles.containerLoader}>
<ActivityIndicator size="large" color={Color.letter} />
</View>
)
}
const onSelectedEnlarge = ( select, order ) => {
setOrder(order)
setSelected(select);
};
/*
let content = <Super onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
if (!selected) {
content = <Super onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
}
else
{
content = <ListSuper onSelectedEnlarge={onSelectedEnlarge} object = {order}/>;
}
*/
return (
<Provider store={store}>
<AppNavigator/>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: Color.primary,
color: Color.letter,
fontFamily: 'Lato-Regular',
},
});
thanks for your help
How can I send props to another file?
I have a component file. And there is an array where data are pushed. If the user click ok, then I want the array to another file.
example:
sizeComponent.js
import React from 'react';
import { StyleSheet, View, Text, TouchableOpacity, FlatList, Dimensions } from 'react-native';
import pure from 'recompose/pure';
const width = Dimensions.get('window').width;
const height = Dimensions.get('window').height;
const AboveSize = ({ data, onPress }) => {
return (
<View style={{marginTop: 10}}>
<Text style={{color: '#333', fontSize: 16}}>Bekleidungsgröße</Text>
<View style={{flexDirection: 'row', flexWrap: 'wrap'}}>
<FlatList
data={data}
keyExtractor={item => item.key}
horizontal
getItemLayout={(data, index) => {
return {
index,
length: 200,
offset: height * index
}
}}
showsHorizontalScrollIndicator={false}
renderItem={({ item }) => {
return (
<TouchableOpacity onPress={onPress} style={{borderWidth: 1, borderColor: '#ccc', justifyContent: 'center', alignItems: 'center', borderRadius: 8, height: 77, width: 77, margin: 12, marginLeft: 0, backgroundColor: data.includes(item.size) ? 'red' : 'blue'}}>
<Text style={{color: data.includes(item.size) ? '#fff' : '#333', fontSize: 20}}>{item.size}</Text>
</TouchableOpacity>
)
}}
/>
</View>
</View>
)
};
export default pure(AboveSize);
Main.js
import SizeComponent from 'sizeComponent';
/* Size from Mock Data */
const productData = [
{
item: {
id: 1,
name:"Calvin Klein Bag",
price:"29.99€",
size: [
{
key: "1",
size: "XS"
},
{
key: "2",
size: "S",
},
{
key: "3",
size: "M"
},
{
key: "4",
size: "L"
},
{
key: "5",
size: "XL"
},
{
key: "6",
size: "XXL"
},
{
key: "7",
size: "XXXL"
}
],
}
}];
const [productSize, setProductSize] = useState([]);
...
<SizeComponent data={productData} onPress={() => console.log('I want here the data from the component file which was selected')}
In the sizeComponent.js change the onPress method to the following code:
<TouchableOpacity onPress={()=>onPress(item)}
so when the onPress is called the selected item will be passed to the callback method which you can access like this
<SizeComponent data={productData} onPress={(item) => {//the seleteced item will be accessible here })
React Native applications are built using components that manage state internally.
To globalize your state there is a state management libraries like Redux exist to solve this issue. Redux provides a central location for all the states of an application where each component can access the values stored in the state.
reducer.js
import { combineReducers } from "redux";
const INITIAL_STATE = { table:[] };
const reducers = (state = INITIAL_STATE, action) => {
switch (action.type) {
case "PUSH_TABLE":
state.table.push(action.value)
return { ...state, table: state.table };
default:
return state;
}
};
export default combineReducers({ reducers: reducers });
action.js
export const pushTable = (title) => ({
type: "PUSH_TABLE",
value: title
});
app.js
import React from "react";
import ListScreen from "./src/ListScreen";
import ModalScreen from "./src/ModalScreen";
import { NavigationContainer } from "#react-navigation/native";
import { createStackNavigator } from "#react-navigation/stack";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducer from "./src/reducer";
const store = createStore(reducer);
const Stack = createStackNavigator();
function MainStackNavigator() {
return (
<NavigationContainer>
<Stack.Navigator>
<Stack.Screen name="List" component={ListScreen} />
<Stack.Screen name="Modal" component={ModalScreen} />
</Stack.Navigator>
</NavigationContainer>
);
}
export default function App() {
return (
<>
<Provider store={store}>
<MainStackNavigator />
</Provider>
</>
);
}
Table.js
import React from "react";
import { Button } from "react-native";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { pushTable } from "./action";
class Table extends React.Component {
render() {
return (
<>
<Button
title={"PUSH TABLE"}
onPress={() => this.props.pushTable("NICE") }
/>
{this.props.reducers.table.map((cel, index) => (
<Text>{cel} {index}</Text>
))}
</>
);
}
}
const mdtp = (dispatch) => bindActionCreators( { pushTable, }, dispatch );
const mtp = (state) => {
const { reducers } = state;
return { reducers };
};
export default connect(mtp, mdtp)(Table);
I need to pass data from one screen to anothre, an main screen loads and then loads the data from a mock api, it sets the state with providerData, then navigation gets created. I want to be able to use the data i got in the ProviderDetailScreen.js in ProviderOverview.js
Here is ProviderDetailsScreen.js
import React from 'react';
import {StatusBar, View} from 'react-native';
import ProviderOverview from './ProviderOverview';
import ProviderServicesList from './ProviderServicesList';
import NavigationbarHeaderWithExpandedImage from '../components/NavigationbarHeaderWithExpandedImage';
import TopTabbarComponent from '../components/TopTabbarComponent';
import mockApi from '../mockApi';
const ProviderDetailScreen = ({navigation, route}) => {
const [providerData, setProviderData] = React.useState({});
const [loading, setLoading] = React.useState(false);
//navigation setup
React.useLayoutEffect(() => {
navigation.setOptions({
header: ({scene, previous}) => {
return (
<NavigationbarHeaderWithExpandedImage
scene={scene}
previous={previous}
navigation={navigation}
backgroundImage={providerData?.profile?.backgroundImage}
/>
);
},
});
}, [navigation, providerData]);
//get results from API
const getServices = React.useCallback(async () => {
try {
setLoading(true);
const res = await mockApi.get('/Provider/Profile');
if (res.ok && res.body.data) {
// use this data in overview and service list
setLoading(false);
setProviderData(res.body.data);
} else {
throw new Error('Unable to retrieve profile');
}
} catch (error) {
console.log(error);
}
}, []);
React.useEffect(() => {
console.warn('here');
getServices();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
<>
<StatusBar barStyle="light-content" />
<TopTabbarComponent
items={[
{
title: 'Overview',
component: ProviderOverview,
},
{
title: 'Services',
component: ProviderServicesList,
},
{
title: 'Reviews',
component: View,
},
]}
/>
</>
);
};
export default ProviderDetailScreen;
Here is The ToTabbarComponent.js that created a tab for each item in providerdetailsscreen
import React from 'react';
import {StyleSheet} from 'react-native';
import {createMaterialTopTabNavigator} from '#react-navigation/material-top-tabs';
import {PRIMARY, WHITE, INACTIVE_TINT_COLOR, ACCENT} from '../lib/colors';
import fonts from '../lib/fonts';
const Tab = createMaterialTopTabNavigator();
const TopTabbarComponent = ({items}) => {
const tabs = () => {
let tabs = [];
// loop to create tabs
for (const [index, item] of items.entries()) {
tabs.push(
<Tab.Screen
name={item.title}
title={item.title}
component={item.component}
key={index}
/>,
);
}
return tabs;
};
return (
<Tab.Navigator
tabBarOptions={{
activeTintColor: WHITE,
labelStyle: [styles.labelStyle, fonts.medium],
inactiveTintColor: INACTIVE_TINT_COLOR,
style: styles.style,
indicatorStyle: styles.indicatorStyle,
}}>
{tabs()}
</Tab.Navigator>
);
};
const styles = StyleSheet.create({
tabBarOptions: {},
labelStyle: {
fontSize: 14,
},
indicatorStyle: {
backgroundColor: ACCENT,
height: 2,
},
style: {
backgroundColor: PRIMARY,
},
});
export default TopTabbarComponent;
Here is the ProviderOverview.js where i want to use that data that gets set in ProviderDetailsScreen.js
//WANT TO USE DATA HERE
import React from 'react';
import {StyleSheet, View, ScrollView, Text} from 'react-native';
import MediumText from '../components/MediumText';
const ProviderOverview = ({navigation}) => {
return (
<ScrollView style={styles.container}>
<View>
<MediumText onPress={() => navigation.push('PROVIDER_MESSAGE')}>
Send a message
</MediumText>
</View>
<View></View>
</ScrollView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default ProviderOverview;
I am still learning: Things i have tried:
In providerDetailsscreen i tried to set providerdata for each item, i tried setting a test var with some string to see if i can get it in ProviderOverview. But providerOverview only has Navigation prop.
Thanks in advance.
Try this way
ProviderDetailsScreen.js
<TopTabbarComponent
items={[
{
title: 'Overview',
component: ProviderOverview,
providerData: providerData, // set providerData to ProviderOverview
},
{
title: 'Services',
component: ProviderServicesList,
},
{
title: 'Reviews',
component: View,
},
]}
/>
TopTabbarComponent
// loop to create tabs
for (const [index, item] of items.entries()) {
const CompView = item.component;
const providerData = item.providerData || {};
tabs.push(
<Tab.Screen name={item.title} title={item.title} key={index}>
{(props) => <CompView {...props} {...providerData} />}
</Tab.Screen>
);
}
You can use navigation props
this.props.navigation.navigate('MyData', {data: data,});
https://reactnavigation.org/docs/navigation-prop/#navigate
Or add redux to your project https://redux.js.org/introduction/getting-started
Lately i've been trying to link my js on component folder but suddenly the issue came out. The first issue is referrence error which occurs because i make typo mistakes on import section. But then ,on 2nd trial by running the emulator i got 'Type Error: Undefined is not an object (props.albums.title)'
Here's my Card.js
import React from 'react';
import { View } from 'react-native';
const Card = (props) => {
return (
<View style={styles.containerStyle}>
{props.children}
</View>
);
};
const styles = {
containerStyle: {
borderWidht: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTOp: 10
}
};
export default Card;
here is the AlbumDetail
import React from 'react';
import { Text } from 'react-native';
import Card from './Card';
const AlbumDetail = (props) => {
return (
<Card>
<Text>{props.album.title}</Text>
</Card>
);
};
export default AlbumDetail;
here is the AlbumList
import React, { Component } from 'react';
import { View } from 'react-native';
import axios from 'axios';
import AlbumDetail from './AlbumDetail';
class AlbumList extends Component {
state={ albums: [] };
componentWillMount() {
axios.get('https://rallycoding.herokuapp.com/api/music_albums')
.then(response => this.setState({ albums: response.data }));
}
renderAlbums() {
return this.state.albums.map(album => <AlbumDetail key={album.title} record={album} />);
}
render() {
console.log(this.state);
return (
<View>
{this.renderAlbums()}
</View>
);
}
}
export default AlbumList;
You must catch the error 'undefined' which is generated by the array.You declare empty array in state.
renderAlbums(){
if(this.state.albums=='undefined'){
//handle Error
}else{
return this.state.albums.map(album => <AlbumDetail key={album.title} record={album} />)
}
I am using react-navigation and need by clicking the button sign in from welcomescreen move to signin page while its not working.
https://i.stack.imgur.com/w9vfX.png
Here is my code
1. app.js
StyleSheet, Text, View } from 'react-native';
import { TabNavigator, DrawerNavigator, StackNavigator } from 'react-navigation';
import WelcomeScreen from './screens/WelcomeScreen';
import SigninScreen from './screens/SigninScreen';
import SignupScreen from './screens/SignupScreen';
import HomeScreen from './screens/HomeScreen';
import BusinessScreen from './screens/BusinessScreen';
import TechScreen from './screens/TechScreen';
import EducationScreen from './screens/EducationScreen';
import LifestyleScreen from './screens/LifestyleScreen';
import ProfileScreen from './screens/ProfileScreen';
import FavoritesScreen from './screens/FavoritesScreen';
import SettingsScreen from './screens/SettingsScreen';
export default class App extends React.Component {
render() {
const MainNavigator = StackNavigator({
welcome: { screen: WelcomeScreen },
signin: { screen: SigninScreen },
signup: { screen: SignupScreen },
main: {
screen: DrawerNavigator({
home: { screen: HomeScreen },
business: { screen: BusinessScreen },
tech: { screen: TechScreen },
education: { screen: EducationScreen},
lifestyle: { screen: LifestyleScreen },
profile: {
screen: StackNavigator({
profile: { screen: ProfileScreen },
settings: { screen: SettingsScreen }
})
}
},
)
}
},)
return (
<MainNavigator />
);
}
}
2. WelcomeScreen
import React, { Component } from 'react';
import { View, Text} from 'react-native';
import Slides from '../components/Slides';
import PropTypes from 'prop-types';
const SLIDE_DATA = [
{ text: 'Welcome to JobApp', color: '#03A9F4' },
{ text: 'Use this to get a job', color: '#009688' },
{ text: 'Set your location, then swipe away', color: '#03A9F4' }
];
class WelcomeScreen extends Component {
render (){
onSlidesComplete = () => {
this.props.navigation.navigate('signin');
}
return (
<Slides data={SLIDE_DATA} onComplete={this.onSlidesComplete} />
);
}
}
export default WelcomeScreen;
3. Slide.js
import React, { Component } from 'react';
import { View, Text, ScrollView, Button, Dimensions } from 'react-native';
import PropTypes from 'prop-types';
const SCREEN_WIDTH = Dimensions.get('window').width;
class Slides extends Component {
renderLastSlide(index) {
if (index === this.props.data.length - 1) {
return (
<Button raised onPress={this.props.onComplete}
buttonStyle={styles.buttonStyle}
title="Sign In"
>
Sign In
</Button>
);
}
}
renderSlides() {
return this.props.data.map((slide, index) => {
return (
<View
key={slide.text}
style={[styles.slideStyle, { backgroundColor: slide.color }]}
>
<Text style={styles.textStyle}>{slide.text}</Text>
{this.renderLastSlide(index)}
</View>
);
});
}
render() {
return (
<ScrollView
horizontal
style={{ flex: 1 }}
pagingEnabled
>
{this.renderSlides()}
</ScrollView>
);
}
}
const styles = {
slideStyle: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
width: SCREEN_WIDTH
},
textStyle: {
fontSize: 30,
color: 'white'
},
buttonStyle: {
backgroundColor: '#0288D1',
marginTop: 15
}
};
export default Slides;
In WelcomeScreen if you are using arrow function like
onSlidesComplete = () => {
this.props.navigation.navigate('signin');
}
then you have to use the onPress like this.onSlidesComplete.bind(this) or if you are using the function like
onSlidesComplete() {
this.props.navigation.navigate('signin');
}
then you have to use the onPress like this.onSlidesComplete. In short replace the below code with your existing WelcomeScreen
import React, { Component } from 'react';
import { View, Text} from 'react-native';
import Slides from '../components/Slides';
import PropTypes from 'prop-types';
const SLIDE_DATA = [
{ text: 'Welcome to JobApp', color: '#03A9F4' },
{ text: 'Use this to get a job', color: '#009688' },
{ text: 'Set your location, then swipe away', color: '#03A9F4' }
];
class WelcomeScreen extends Component {
render (){
onSlidesComplete = () => {
this.props.navigation.navigate('signin');
}
return (
<Slides data={SLIDE_DATA} onComplete={this.onSlidesComplete.bind(this)} />
);
}
}
export default WelcomeScreen;