Could not find "store" in context of "Connect(Login)" , and I could't find a solution for it here is my code - react-native

//App.js
import React, { Component } from 'react';
import { StyleSheet, Platform, Image, Text, View } from 'react-native';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import rootReducer from './reducers/index';
import Profile from './Screens/Profile';
import Signup from './Screens/Signup';
import Login from './Screens/Login';
const middleware = applyMiddleware(thunkMiddleware);
const store = createStore(rootReducer, middleware);
import { ReactReduxContext } from "react-redux";
const Switch = createSwitchNavigator({
Login: Login,
Profile: Profile,
Signup: Signup
}, {
initialRouteName: 'Login',
});
export default createAppContainer(Switch)
class App extends React.Component {
render() {
return (
<Provider>
<Switch />
</Provider>
)
}
}
//Login.js
import React from 'react';
import Firebase from '../config/firebase';
import Signup from '../Screens/Signup';
import Profile from '../Screens/Profile';
import { createSwitchNavigator } from 'react-navigation';
import { View, TextInput, StyleSheet, TouchableOpacity, Text, Button } from 'react-native';
import ReactReduxContext from 'react-redux';
import { bindActionCreators, applyMiddleware, createStore, Provider } from 'redux';
import { connect } from 'react-redux';
import { updateEmail, updatePassword, login } from '../actions/user';
import thunkMiddleware from 'redux-thunk';
function mapDispatchToProps(dispatch) {
return bindActionCreators({ login, updateEmail, updatePassword }, dispatch)
}
const mapStateToProps = state => {
return {
user: user.state
}
}
class Login extends React.Component {
handle = () => {
this.props.login()
this.props.navigation.navigate('Profile')
}
state = {
email: '',
password: ''
}
render() {
return (
<Provider>
<View style={styles.container}>
<TextInput
style={styles.inputBox}
value={this.state.email}
onChangeText={email => this.props.updateEmail(email)}
placeholder='Email'
autoCapitalize='none'
/>
<TextInput
style={styles.inputBox}
value={this.state.password}
onChangeText={password => this.props.updatePassword(password)}
placeholder='Password'
secureTextEntry={true}
/>
<TouchableOpacity style={styles.button} onPress={this.handleLogin}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<Button title="Don't have an account yet? Sign up"
onPress={() => this.props.navigation.navigate('Signup')} />
</View>
</Provider>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center'
},
inputBox: {
width: '85%',
margin: 10,
padding: 15,
fontSize: 16,
borderColor: '#d3d3d3',
borderBottomWidth: 1,
textAlign: 'center'
},
button: {
marginTop: 30,
marginBottom: 20,
paddingVertical: 5,
alignItems: 'center',
backgroundColor: '#F6820D',
borderColor: '#F6820D',
borderWidth: 1,
borderRadius: 5,
width: 200
},
buttonText: {
fontSize: 20,
fontWeight: 'bold',
color: '#fff'
},
buttonSignup: {
fontSize: 12
}
})
export default connect(
mapStateToProps,
mapDispatchToProps
)(Login);

In order to access the connect HOC, you first need to provide the store to the UI tree via the Provider
You can do it like this:
class App extends React.Component {
render() {
return (
<Provider store={store}> // this is what is required.
<Switch />
</Provider>
)
}
}
Hope this helps. Cheers!

Related

React native: can't configure the header with navigationOptions

I am new to react-native. I am trying to configure header styles for my app, but it's not working
App.js
import { StatusBar } from 'expo-status-bar';
import React, {useState} from 'react';
import { StyleSheet, Text, View } from 'react-native';
import MealNavigator from './navigation/MealsNavigator';
export default function App() {
return (
<MealNavigator />
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
The following js file i am using for navigation
MealsNavigator.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from "react-navigation";
import categoriesScreen from '../screens/categoriesScreen';
import categoryMealScreen from '../screens/categoryMealScreen';
import mealDetailScreen from '../screens/mealDetailScreen';
const MealNavigator = createStackNavigator({
Categories : categoriesScreen,
CategoryMeals : categoryMealScreen,
MealDetail : mealDetailScreen
});
export default createAppContainer(MealNavigator);
The following is the screen where i am trying to configure the header
categoriesScreen.js
import React from 'react';
import {Text,View,Button,FlatList,StyleSheet,TouchableOpacity, Platform} from 'react-native';
import { CATEGORIES } from '../data/dummydata';
const CategoriesScreen = props => {
const renderGrid=(itemData) =>{
return(
<TouchableOpacity style={styles.gridItem} onPress={() =>{props.navigation.navigate({routeName:'CategoryMeals'});}}>
<View>
<Text>{itemData.item.title}</Text>
</View>
</TouchableOpacity>
)
};
return(
<View style={styles.container}>
<FlatList
data={CATEGORIES} renderItem={renderGrid} numColumns={2} />
</View>
);
}
CategoriesScreen.defaultNavigationOptions = ({ navigation }) =>({
title:'Meal Categories',
headerTitleStyle: {
textAlign: "left",
fontSize: 24
},
});
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
gridItem:{
flexGrow:1,
padding: 20,
margin: 15,
height: 150,
}
});
export default CategoriesScreen;
The following is the dummy data i am using
dummydata.js
import Category from '../models/category';
export const CATEGORIES = [
new Category('c1','Indian','#f5428d'),
new Category('c2','Chinese','#f54242'),
new Category('c3','Thai','#f5a442'),
new Category('c4','Malaysian','#f5d142'),
new Category('c5','Arabian','#368dff'),
new Category('c6','South Indian','#41d95d'),
new Category('c7','Kerala','#9eecff'),
new Category('c8','Bengali','#b9ffb0'),
new Category('c9','Mexican','#ffc7ff'),
new Category('c10','Italian','#47fced'),
];
Following is category class file
category.js
class Category{
constructor(id,title,color){
this.id = id;
this.title = title;
this.color = color;
}
};
export default Category;
Everything else is working, just the header configuration is not working.I am using react navigation version 4
you can cofigure header using navigation.setOptions like this:
import React from 'react';
import {Text,View,Button,FlatList,StyleSheet,TouchableOpacity, Platform} from 'react-native';
import { CATEGORIES } from '../data/dummydata';
const CategoriesScreen = props => {
React.useLayoutEffect(() => {
props.navigation.setOptions({
headerTitle: 'Meal Categories',
headerTitleStyle: {
textAlign: "left",
fontSize: 24
},
});
},
const renderGrid=(itemData) =>{
return(
<TouchableOpacity style={styles.gridItem} onPress={() =>{props.navigation.navigate({routeName:'CategoryMeals'});}}>
<View>
<Text>{itemData.item.title}</Text>
</View>
</TouchableOpacity>
)
};
return(
<View style={styles.container}>
<FlatList
data={CATEGORIES} renderItem={renderGrid} numColumns={2} />
</View>
);
}
const styles = StyleSheet.create({
container:{
flex:1,
justifyContent:'center',
alignItems:'center'
},
gridItem:{
flexGrow:1,
padding: 20,
margin: 15,
height: 150,
}
});
export default CategoriesScreen;
I found a different solution to my problem. I used defaultNavigationOptions in my navigation file.
MealsNavigator.js
import { createStackNavigator } from 'react-navigation-stack';
import { createAppContainer } from "react-navigation";
import categoriesScreen from '../screens/categoriesScreen';
import categoryMealScreen from '../screens/categoryMealScreen';
import mealDetailScreen from '../screens/mealDetailScreen';
import {Platform} from 'react-native';
import colors from '../constants/colors';
const MealNavigator = createStackNavigator({
Categories : {
screen : categoriesScreen,
navigationOptions : {
headerTitle:'Meal Categories',
}
},
CategoryMeals : {
screen : categoryMealScreen
},
MealDetail : mealDetailScreen
},
{
defaultNavigationOptions:{
headerTitleStyle:{
backgroundColor:Platform.OS==='android' ? colors.primaryColor : 'white'
},
headerTintColor:Platform.OS==='android' ? 'white' : colors.primaryColor
}
}
);
export default createAppContainer(MealNavigator);
Thanks to everybody for your help.

Error: undefined is not an object (evaluating 'this.props.navigation.navigate')

I have created a separate route file and when I am trying to navigate between screens with the help of these routes with react-navigation using stackNavigator I am getting this error I have already tried other solutions available on Stack overflow but none of the answers solve my problem here is my code.
This is my Route.js file
import { createAppContainer, createStackNavigator } from 'react-navigation';
import Login from './screens/Login';
import Register from './screens/Register';
import Start from './screens/Start';
const AppNavigator = createStackNavigator({
Home: {
screen: Start,
},
LoginScreen: {
screen: Login,
},
RegisterScreen: {
screen: Register,
},
}, {
initialRouteName: 'Home',
navigationOptions: {
header: null
}
});
export default createAppContainer(AppNavigator);
And this is my component where I am trying to navigate
import React,{ Component } from 'react';
import { StyleSheet, View, KeyboardAvoidingView,Text } from 'react-native';
import NewButtons from './NewButtons';
import Logo from './Logo';
export default class Start extends Component{
constructor () {
super();
}
loginPress = () => {
this.props.navigation.navigate('LoginScreen');
}
registerPress = () => {
this.props.navigation.navigate('RegisterScreen');
}
render(){
return(
<KeyboardAvoidingView behavior='padding' style={styles.wrapper}>
<View style={styles.logoContainer}>
<Logo/>
<Text style={styles.mainHead}>Welcome to Food Zone</Text>
<Text style={{margin: 10, textAlign:'center'}}>Check out our menus, order food and make reservations{"\n"}{"\n"}</Text>
<NewButtons text="Login"
onPress={this.loginPress}/>
<NewButtons text="Register"
onPress={this.registerPress}/>
</View>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
logoContainer: {
alignItems: 'center',
},
mainHead: {
fontFamily: 'PatuaOne',
color: '#ff9900',
fontSize: 28,
marginTop: -50,
},
})
And this in my button component
import React,{ Component } from 'react';
import { StyleSheet, View,Dimensions } from 'react-native';
import { Button, Text } from 'native-base';
const {width:WIDTH} = Dimensions.get('window')
export default class NewButtons extends Component{
constructor(props){
super(props);
}
handlePress = () => {
this.props.onPress();
}
render(){
return(
<View style={styles.ButtonContainer}>
<Button light style={styles.mainButtons} onPress={this.handlePress()}>
<Text style={styles.textProps}>{this.props.text}</Text>
</Button>
</View>
);
}
}
const styles = StyleSheet.create({
textProps:{
fontFamily: 'PatuaOne',
color: '#ffffff',
},
mainButtons: {
backgroundColor: "#ff9900",
width: 250,
margin: 5,
color: '#ffffff',
justifyContent: 'center',
width: WIDTH -75,
borderRadius: 10,
},
ButtonContainer: {
alignItems: 'center',
}
})
I managed to remove this error by importing routes in App.js file and by calling it in index.js here is my code of App.js file.
import React, {Component} from "react";
import Routes from "./Routes";
const App = () => <Routes/>
export default App;

While adding navigation PLugin its not Working showing error

New to react-native and trying to make react-native with the sample app.
I created Two Screen. LOGIN AND FORM Screen.
I want Once I clicked to login button it will go to form screen. I add library of navigation for routing.
But it shows error.
App.js
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import {StackNavigator} from 'react-navigation';
import Login from './src/pages/pages/Login';
import Form from './src/pages/pages/Form';
const AppNavigator = StackNavigator({
Login: { screen: Login},
Form: { screen: Form},
});
export default class App extends Component<{}> {
render() {
return (
<View style ={styles.container}>
<AppNavigator/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
}
})
Login.js
import React, {Component} from 'react';
import {
StyleSheet,
Text,
View,
TextInput,
Button,
TouchableOpacity
} from 'react-native';
export default class Login extends Component {
state = {
username: '', password: ''
}
onChangeText = (key, val) => {
this.setState({ [key]: val })
}
signUp = async () => {
const { username, password } = this.state
try {
// here place your signup logic
console.log('user successfully signed up!: ', success)
} catch (err) {
console.log('error signing up: ', err)
}
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.input}
placeholder='Username'
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('username', val)}
/>
<TextInput
style={styles.input}
placeholder='Password'
secureTextEntry={true}
autoCapitalize="none"
placeholderTextColor='white'
onChangeText={val => this.onChangeText('password', val)}
/>
<TouchableOpacity
style={styles.button}
onPress={() => this.props.navigation.navigate('Form') } title = "Form"
>
<Text > LOGIN </Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
input: {
width: 350,
height: 55,
backgroundColor: '#ff4000',
margin: 10,
padding: 8,
color: 'white',
borderRadius: 4,
fontSize: 18,
fontWeight: '500',
},
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
button: {
alignItems: 'center',
backgroundColor: '#58d63b',
padding: 10,
width:320,
height:55
}
})
Form.js
import React, {Component} from 'react';
import {View,Text} from 'react';
export default class Login extends Component {
render() {
return (
<View>
<Text> This Is Form Page</Text>
</View>
);
}
}
index.js
import {AppRegistry} from 'react-native';
import App from './App';
import {name as appName} from './app.json';
AppRegistry.registerComponent(appName, () => App);
THIS IS THE ERROR I HAVE GETTING ALL THE TIME
I tried everything clear cache and re-install npm but no luck.
Anyone can help.It would be great.

Unable to connect mapStateToProps and mapDispatchToProps

I'm getting an error that undefined is not a function(evaluating 'this.props.addTodo(text)')
my code was working fine before i introduces the react-navigation as after that i want to add a todo from my second screen i.e. Counter and want to see whether the list on screen one gets updated or not. but i got stuck at adding a todo on first screen as it is throwing the above error.
I'm a complete begginner in React-native and Redux and also in Js. Btw thanks and in advance
and here is my code:
App.js
import React from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import TodoApp from './src/TodoApp'
import store from './app/store/index'
import { Provider } from 'react-redux'
import {CounterR} from './app/counterR';
import {Counter} from './app/counter';
import {createStackNavigator, createAppContainer} from 'react-
navigation'
export default class App extends React.Component {
render() {
return (
<Provider store={store}>
<AppContainer />
</Provider>
);
}
}
const stack = createStackNavigator({
Home: CounterR,
Second: Counter
},{
initialRouteName: 'Home'
})
const AppContainer = createAppContainer(stack)
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
CounterR.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import {NavigationAction} from 'react-navigation'
import store from './store/index'
import { Provider } from 'react-redux'
const { width, height } = Dimensions.get("window");
export class CounterR extends Component{
state = {
text: ""
}
add = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text:value})}/>
<TouchableOpacity
onPress={() => this.add(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.props.navigation.navigate('Second')}>
<Text
style={{fontSize: 18}}>Second Screen</Text>
</TouchableOpacity>
<FlatList
data= {this.props.todos}
numColumns={1}
keyExtractor= {item => item.id}
renderItem ={({ item }) =>
<TouchableOpacity
onPress={() => this.props.toggleTodo(item)}
style={styles.todoText}>
<Text style={{textDecorationLine: item.completed ? 'line-through' : 'none', fontSize: 20}}>{item.text}</Text>
</TouchableOpacity>
}
/>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(CounterR)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
todoText: {
width: width,
margin: 10
}
});
Counter.js
import React, { Component } from 'react';
import {View,
TouchableOpacity,
Text,
Dimensions,
StyleSheet,
TextInput,
FlatList,
Keyboard} from 'react-native';
import {connect} from 'react-redux'
import { addTodo } from './actions/index'
import { toggleTodo } from './actions/index'
import { Provider } from 'react-redux'
import store from './store/index'
const { width, height } = Dimensions.get("window");
export class Counter extends Component{
state = {
text: "",
}
addTodo = text => {
Keyboard.dismiss()
this.props.addTodo(text)
this.setState({text: ""})
}
render(){
return(
<View style={styles.container}>
<TextInput
style={{borderWidth:.5, width: 300, height: 40}}
defaultValue={this.state.text}
onChangeText={(value) => this.setState({text: value})}/>
<TouchableOpacity
onPress={() => this.addTodo(this.state.text)}>
<Text
style={{fontSize: 18}}>ADD TODO</Text>
</TouchableOpacity>
</View>
)
}
}
const mapStateToProps = state => ({
todos: state.todos
})
const mapDispatchToProps = dispatch => ({
addTodo: text => dispatch(addTodo(text)),
toggleTodo: item => dispatch(toggleTodo(item))
})
export default connect(mapStateToProps, mapDispatchToProps)(Counter)
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
todoText: {
width: width,
margin: 10
}
});
app/actions/index.js
import {Keyboard} from 'react-native'
import { ADD_TODO, TOGGLE_TODO } from './actionTypes'
let x = 0
export const addTodo = (text) => ({
type: ADD_TODO,
id: x++,
text: text
})
export const toggleTodo = (item) => ({
type: TOGGLE_TODO,
id: item.id
})
app/actions/actionTypes.js
export const ADD_TODO = 'ADD_TODO'
export const TOGGLE_TODO = 'TOGGLE_TODO'
app/reducers/index.js
import { combineReducers } from 'redux'
import todos from './todos'
export default combineReducers({
todos
})
app/reducers/todos.js
const todos = (state =[], action) => {
switch(action.type){
case 'ADD_TODO':
return [
...state, {
id: action.id,
text: action.text,
completed: false
}
]
case 'TOGGLE_TODO':
return state.map(todo =>
(todo.id === action.id)
?
{...todo, completed: !todo.completed}
:
todo)
default:
return state
}
}
export default todos
app/store/index.js
import { createStore } from 'redux'
import rootReducer from '../reducers'
export default store = createStore(rootReducer)

React Native Auth with React Navigation and Redux

I have just started integrating Redux into my first React Native (Expo.io) project. I have got login working great with Redux, but when I try and create a logout button on one of the screens in my app, it actually triggers the log out dispatch as soon as it loads it. I think I must be misunderstanding the way Redux connect and mapDispatchToProps work. I have read the documentation many times but am still stuck. Here is the code in it's non-working state.
Log In - Works until I add the log out dispatch on profile page
import { connect } from "react-redux";
import React, { Component } from "react";
import {
Button,
View,
Text,
ActivityIndicator,
Alert,
FlatList
} from "react-native";
import { NavigationActions } from "react-navigation";
import { SocialIcon, Card } from "react-native-elements";
import Reactotron from "reactotron-react-native";
import { logIn } from "../actions";
import { signIn } from "../components/Auth";
class SignIn extends Component {
async handleClick() {
res = await signIn();
if (res != false) {
this.props.logIn(res.token);
} else {
console.log("Login Failed");
}
}
render() {
return (
<View style={{ paddingVertical: 20 }}>
<Card title="finis Requires A Facebook Account To Operate">
<SocialIcon
title="Fred"
button
type="facebook"
onPress={() => this.handleClick()}
/>
</Card>
</View>
);
}
}
const mapDispatchToProps = dispatch => {
return {
logIn: fbToken => {
dispatch(logIn(fbToken));
}
};
};
LoginScreen = connect(null, mapDispatchToProps)(SignIn);
export default LoginScreen;
Reducers
import { combineReducers } from "redux";
import Reactotron from "reactotron-react-native";
import { LOG_IN, LOG_OUT, ADD_PHONE_CONTACTS } from "../actions/actions";
const initialState = {
signedIn: false,
fbToken: "fred",
test: undefined,
phoneContacts: {}
};
const finis = combineReducers({
auth,
phoneContacts
});
function auth(state = initialState, action) {
switch (action.type) {
case LOG_IN:
Reactotron.log("LOG IN");
return {
...state,
signedIn: true,
fbToken: action.fbToken
};
case LOG_OUT:
Reactotron.log("LOG OUT");
return {
...state,
signedIn: false,
fbToken: undefined
};
default:
return state;
}
}
function phoneContacts(state = [], action) {
switch (action.type) {
case ADD_PHONE_CONTACTS:
console.log("Adding Contacts");
return {
...state,
phoneContacts: action.phoneContacts
};
default:
return state;
}
}
export default finis;
Profile Non working. Triggers LOG_OUT action without the button being pushed.
import React, { Component } from "react";
import { Button, Card } from "react-native-elements";
import { View, Text, ActivityIndicator, AsyncStorage } from "react-native";
import { MapView } from "expo";
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import { SimpleLineIcons } from "#expo/vector-icons";
import Reactotron from "reactotron-react-native";
import * as ActionCreators from "../actions";
import { signOut } from "../components/Auth";
class ProfileWrap extends Component {
handleClick() {
Reactotron.log(this.Actions);
this.props.logOut();
}
render() {
return (
<View style={{ paddingVertical: 20 }}>
<Card title="Profile">
<View
style={{
backgroundColor: "#bcbec1",
alignItems: "center",
justifyContent: "center",
width: 80,
height: 80,
borderRadius: 40,
alignSelf: "center",
marginBottom: 20
}}
>
<Text style={{ color: "white", fontSize: 28 }}>JD</Text>
</View>
<Button title="Log Out" onPress={this.handleClick} />
</Card>
</View>
);
}
}
mapDispatchToProps = dispatch => {
return {
logOut: dispatch(logOut())
};
};
const Profile = connect(null, mapDispatchToProps)(ProfileWrap);
export default Profile;
Any help would be appreciated, even if it's telling me I'm doing the whole thing wrong :) Been at this for hours.
NEW Profile.js - Gives Cannot read property 'logOut' of undefined
import React, { Component } from "react";
import { Button, Card } from "react-native-elements";
import { View, Text, ActivityIndicator, AsyncStorage } from "react-native";
import { MapView } from "expo";
import { connect } from "react-redux";
import { SimpleLineIcons } from "#expo/vector-icons";
import { logOut } from "../actions";
import { signOut } from "../components/Auth";
class ProfileWrap extends Component {
handleClick() {
console.log(this.props);
this.props.logOut();
}
render() {
return (
<View style={{ paddingVertical: 20 }}>
<Card title="Profile">
<View
style={{
backgroundColor: "#bcbec1",
alignItems: "center",
justifyContent: "center",
width: 80,
height: 80,
borderRadius: 40,
alignSelf: "center",
marginBottom: 20
}}
>
<Text style={{ color: "white", fontSize: 28 }}>JD</Text>
</View>
<Button title="Log Out" onPress={this.handleClick} />
</Card>
</View>
);
}
}
const mapDispatchToProps = dispatch => {
return {
logOut: function() {
dispatch(logOut());
}
};
};
const Profile = connect(null, mapDispatchToProps)(ProfileWrap);
export default Profile;
Your mapDispatchToProps should be returning an object with functions. The way you have it now, logOut() will be called immediately since it's not inside a function. Changing it to this should fix it:
const mapDispatchToProps = dispatch => {
return {
logOut: function () {
dispatch(logOut());
}
};
};
Here's a slightly cleaner way of doing it:
const mapDispatchToProps = dispatch => ({
logOut() {
dispatch(logOut());
}
});
Also, you're missing const in front of mapDispatchToProps but that shouldn't have affected anything.
Edit:
You don't have to use this now, but it'll be helpful in the future - if your component is only using the render method you can change it to a stateless functional component. It's currently the recommended way of creating components when possible:
const ProfileWrap = props => (
<View style={{ paddingVertical: 20 }}>
<Card title="Profile">
<View
style={{
backgroundColor: "#bcbec1",
alignItems: "center",
justifyContent: "center",
width: 80,
height: 80,
borderRadius: 40,
alignSelf: "center",
marginBottom: 20
}}
>
<Text style={{ color: "white", fontSize: 28 }}>JD</Text>
</View>
<Button title="Log Out" onPress={props.logOut} />
</Card>
</View>
);