Setting up Redux with React Native function undefined - javascript

I think I'm close with setting up React Redux for my React native app. I currently have this set up.
Here I define the action that I want to call.
/* actions/mapActions.js */
export const setMarker = selectedMarker => {
return {
type: 'SET_MARKER',
selectedMarker
}
}
Here I define the container for the component that I want to use the store in.
//containers/mapContainers.js
import { connect } from 'react-redux';
import { setMarker } from './actions/mapActions'
import HomeScreen from './screens/HomeScreen'
const mapStateToProps = state => {
return {
selectedMarker: state.marker
}
}
const mapDispatchToProps = dispatch => {
return {
markerClick: (marker) => {
dispatch(setMarker(marker))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen)
Here I combine the reducers as I've seen in a tutorial I've been following.
//reducers/index.js
import { combineReducers } from 'redux'
import mapReducer from './mapReducer'
const dabApp = combineReducers({
mapReducer
})
export default dabApp
Here I define the reducer for the component.
//reducers/mapReducers.js
const mapReducer = (state = [], action) => {
switch (action.type) {
case 'SET_MARKER':
return [
...state,
{
marker: action.marker
}
]
default:
return state
}
}
export default mapReducer
Main entry point to the application.
//App.js
// other imports here
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import snapApp from './reducers';
let store = createStore(dabApp);
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
render() {
return (
<Provider store={store}>
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
{Platform.OS === 'android' &&
<View style={styles.statusBarUnderlay} />}
<RootNavigation />
</View>
</Provider>
);
}
}
const styles = StyleSheet.create({
//Styles.
});
Here I define the component.
//Standard react imports.
import { MapView } from 'expo';
import { connect } from 'react-redux';
export default class HomeScreen extends React.Component {
constructor(props) {
super(props);
this.state = {
//Set states.
};
}
render() {
return (
<View style={styles.container}>
<MapView
//MapView info
>
{this.state.markers.map((marker) =>
<MapView.Marker
key={marker.id}
coordinate={marker.coordinate}
onPress={() => {this.props.markerClick(marker); this.props.navigation.navigate('Information');}}>
</MapView.Marker>
)}
</MapView>
</View>
);
}
}
const styles = StyleSheet.create({
//Styles.
});
The error I get is that the function 'markerClick' is undefined in the Map.Marker onPress prop. I have followed the tutorial religiously and can't find the solution to this.
The tutorial that I was following was this one on the official redux site. http://redux.js.org/docs/basics/ExampleTodoList.html.
Has anyone encountered the same issue?
Unfortunately, Harry's answer hasn't solved the issue.
I console.log(this.props) and I get this:
Still is undefined. When I console.log(this.props") I get:
Object {
"navigation": Object {
"dispatch": [Function anonymous],
"goBack": [Function goBack],
"navigate": [Function navigate],
"setParams": [Function setParams],
"state": Object {
"key": "Home",
"routeName": "Home",
},
},
"screenProps": undefined,
"selectedMarker": [Function dispatch],
"type": "SET_MARKER",
}
so I don't even see the function on my props.
As you can see, the function is not defined on this.props.
Thanks,

I feel like you're making more steps than needed.
Try something like this:
import React, { Component } from 'react';
import { MapView } from 'expo';
import { connect } from 'react-redux';
import { View, StyleSheet } from 'react-native';
import { setMarker } from './actions/mapActions'
class HomeScreen extends Component {
onPress(marker) {
this.props.setMarker(marker);
this.props.navigation.navigate('Information');
}
render() {
return (
<View style={styles.container}>
<MapView>
{this.state.markers.map((marker) => (
<MapView.Marker
key={marker.id}
coordinate={marker.coordinate}
onPress={() => { this.onPress(marker); }}
/>
)
)}
</MapView>
</View>
);
}
}
const styles = StyleSheet.create({
//Styles.
});
export default connect(null, setMarker)(HomeScreen);
You don't need to define a function that then dispatches an action, you can just connect the action to the component.
It's also much nicer to just have everything in the same file instead of having a separate mapContainers.js

Related

ReferenceError: ReferenceError: Can't find variable: dispatch

I'm trying to use redux with react-native. I have created a fetch post data example app , then I just wanted to use with mapDispatchToProps method. I read the documentation and look at some tutorial, it looks similar.
Problem is when I try to use mapDispatchToProps its return error:
ReferenceError: ReferenceError: Can't find variable: dispatch
An error appears in HomeScreen
My Home Screen
import React from 'react';
import { View } from 'react-native';
import { connect } from 'react-redux';
import { getPosts } from '../actions/index';
class HomeScreen extends React.Component {
state = {
data:[],
}
componentDidMount() {
this.props.getPosts()
}
render() {
return (
<View style={styles.container}>
</View>
);
}
}
function mapStateToProps (state) {
return {
posts: state.posts
};
};
function mapDispatchToProps (dispatch) {
return {
getPosts: () => {
dispatch(getPosts())
}
};
};
export default connect(mapStateToProps, mapDispatchToProps)(HomeScreen)
My Store
import { createStore } from 'redux';
import rootReducer from '../reducers';
export default store = createStore(rootReducer);
My Action
import { GET_PGET_POST_LOADING,GET_POST_RECEIVED,GET_POST_ERROR } from './actionTypes';
import { GET_POST_URL } from '../api';
export const getPosts = () => {
dispatch({
type: GET_POST_LOADING
});
fetch(GET_POST_URL).then((data) => {
console.log(data);
dispatch({
type:GET_POST_RECEIVED,
payload:data
})
}).catch((error) => {
console.log(error)
})
}
My Reducer
import { GET_POST_LOADING, GET_POST_RECEIVED, GET_POST_ERROR } from '../actions/actionTypes';
const Post = (state = { posts: [] , loading: true }, action) => {
console.log(action);
switch(action.type) {
case GET_POST_LOADING:
return {
...state,
loading: true
}
case GET_POST_RECEIVED:
return {
loading:false,
posts: action.payload
}
case GET_POST_ERROR:
return state;
default: return state;
}
}
export default Post;
My Appjs
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font, Icon } from 'expo';
import AppNavigator from './navigation/AppNavigator';
import { Provider } from 'react-redux';
import store from './store/index';
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
render() {
return (
<Provider store={store}>
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
<AppNavigator />
</View>
</Provider>
);
}
}
I'm new about Redux, where I'm missing?
Thanks in advance :)

How to use StackNavigator with Redux?

Could please somebody help me to manage with StackNavigator and Redux integration? Everything looks pretty simple, but doesn't work.
index.ios.js
import React from 'react'
import {
AppRegistry
} from 'react-native'
import { Provider } from 'react-redux'
import configureStore from './configureStore'
import { StackNavigator } from 'react-navigation';
import Welcome from "./screens/welcome";
import Accounts from "./screens/accounts";
const store = configureStore()
const Nav = StackNavigator({
Welcome: {
screen: Welcome,
},
Accounts: {
screen: Accounts,
},
});
const TestApp = () => (
<Provider store={store}>
<Nav />
</Provider>
)
AppRegistry.registerComponent('TestApp', () => RNRedux)
configureStore.js
import { createStore } from 'redux'
import rootReducer from './reducers'
export default function configureStore() {
let store = createStore(rootReducer)
return store
}
reducers/index.js
import { combineReducers } from 'redux'
import accounts from './accounts'
const rootReducer = combineReducers({
accounts
})
export default rootReducer
screens/accounts.js
import React from 'react';
import { StyleSheet, Text, View, button } from 'react-native';
import { ListItem } from 'react-native-elements';
import { StackNavigator } from 'react-navigation';
import { connect } from 'react-redux';
export class Accounts extends React.Component {
static navigationOptions = {
title: 'Accounts',
}
constructor(props) {
super(props);
}
render() {
state = {}
const { navigate } = this.props.navigation;
return (
<View>
{
this.props.accounts.map((l, i) => (
<ListItem
key={i}
title={l.title}
subtitle={l.hash}
/>
))
}
</View>
);
}
}
function mapStateToProps (state) {
return {
accounts: state.accounts
}
}
export default connect(
mapStateToProps,
)(Accounts)
reducers/accounts.js
const initialState = {
accounts: [
{
title: "Bitcoin Slash Fund",
hash: "0x83247jfy344fgg",
},
],
}
export default function (state = initialState, action) {
switch (action.type) {
default:
return state;
}
}
When I navigate to Accounts screen, I get the error
TypeError: undefined is not a function (near '...this.props.state.accounts.map...');
Accounts screen seems not to be actually connected to Redux, and I can't figure out why. Any ideas? Thanks a lot.
Try this one:
function mapStateToProps (state) {
// Just FYI here you can use console.log to see the state)
// console.log(state);
return {
accounts: state.accounts.accounts
}
}
you could see console.log output in Xcode or in AndroidStudio.
Don't use Redux to manage the state of navigator. refer to this official doc: https://reactnavigation.org/docs/en/redux-integration.html
In my case, if you just want the title of navigator changed when the Redux state changes, just use screenProps, refer to: Passing screenProps to a tab navigator
e.g. in your App.js render method, pass screenProps into the target component,
import { LoginStackNavigator } from './navigators/LoginStackNavigator'
render () {
return (
<LoginStackNavigator screenProps={
{
// Step1. pass the value into the navigator component instance.
tradeTitle: i18n.t('trade', {locale: this.props.language}),
}
}/>
)
}
and in the related file, ( such as LoginStackNavigator.js in my case),
import { AppTabNavigator } from '../navigators/AppTabNavigator'
export const LoginStackNavigator = createStackNavigator({
Trade: {
screen: AppTabNavigator
}
//...
and in the final file ( AppTabNavigator)
export const AppTabNavigator = createBottomTabNavigator({
TradeStackNavigator: {
screen: TradeStackNavigator,
navigationOptions: ({navigation, navigationOptions, screenProps}) => {
return {
// Step2. here use screenProps to retrieve the value passed in .
tabBarLabel: screenProps.tradeTitle,
}
}

Mobx injector store not available in React Native app

I am getting an error "MobX injector: Store 'systemStore' is not available! make sure it is provided by some provider. What I really need to do is pass the store to all of my components so that I hace access to them in the this.props.systemStore in like, componentWillMount
import React from 'react';
import { Platform, StatusBar, StyleSheet, View } from 'react-native';
import { AppLoading, Asset, Font } from 'expo';
import { Ionicons } from '#expo/vector-icons';
import {NavigationActions} from 'react-navigation'
import RootNavigation from './navigation/RootNavigation';
import { inject, observer, Provider } from 'mobx-react';
import { observable, action } from "mobx";
import SystemStore from "./stores/SystemStore";
class Main extends React.Component {
render() {
return (
<Provider systemStore={SystemStore} >
<App />
</Provider>
);
}
}
#inject("systemStore")
export default class App extends React.Component {
state = {
isLoadingComplete: false,
};
render() {
if (!this.state.isLoadingComplete && !this.props.skipLoadingScreen) {
return (
<AppLoading
startAsync={this._loadResourcesAsync}
onError={this._handleLoadingError}
onFinish={this._handleFinishLoading}
/>
);
} else {
return (
<View style={styles.container}>
{Platform.OS === 'ios' && <StatusBar barStyle="default" />}
{Platform.OS === 'android' &&
<View style={styles.statusBarUnderlay} />}
<RootNavigation />
</View>
);
}
}
_loadResourcesAsync = async () => {
return Promise.all([
Font.loadAsync([
// This is the font that we are using for our tab bar
Ionicons.font,
// We include SpaceMono because we use it in HomeScreen.js. Feel free
// to remove this if you are not using it in your app
{ 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
]),
Asset.loadAsync([
require('./assets/images/robot-dev.png'),
require('./assets/images/robot-prod.png'),
]),
]);
};
_handleLoadingError = error => {
console.warn(error);
};
_handleFinishLoading = () => {
this.setState({ isLoadingComplete: true });
};
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
statusBarUnderlay: {
height: 24,
backgroundColor: 'rgba(0,0,0,0.2)',
},
});
Expo.registerRootComponent(Main);
and the store looks like this
import {observable, action, computed} from 'mobx'
class SystemStore {
#observable loggedIn = false;
#observable controlAuth = false;
#observable testingKey = "Testing-Yo"
}
export default new SystemStore()
i have been all over looking for a solution, just cannot seem to get my head around this one. thanks
So how I deal with this issue is, I create a file called stores.js which looks like this:
import SystemStore from './stores/systemStore';
const systemStore = new SystemStore();
export {
SystemStore
}
export default {
systemStore
}
In this file I import and export all my stores, so that I can always call stores.systemStore (and all other stores you have) with just importing my stores.js like this
import React from 'react';
import {observer} from 'mobx-react';
import stores from './../../stores';
#observer
class TestComponent extends React.Component {
constructor(props){
super(props);
}
render() {
return (
<div>
{stores.systemStore.testingKey}
</div>
);
}
}
export default TestComponent;
And my stores look like this then:
import store from 'store';
import {observable, action, computed} from 'mobx';
class systemStore {
#observable loggedIn = false;
#observable controlAuth = false;
#observable testingKey = "Testing-Yo";
}
export default systemStore;
I hope this will help you. It works for me :)

Why am I getting an invalid value error?

I don't understand how I'm getting this error (pic below). In my LoginForm.js file, the onEmailChange(text) is giving me an unresolved function or method call to onEmailChange() error when I hover over it in my WebStorm IDE. In my index.js file, no error is being thrown anywhere.
I've looked around SO for this issue but it doesn't fully pertain to my problem.
I've tried File > Invalidate Caches/Restart but that didn't work.
Here's App.js:
import React, { Component } from 'react';
import {StyleSheet} from 'react-native';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import firebase from 'firebase';
import reducers from './reducers';
import LoginForm from './components/common/LoginForm';
class App extends Component {
render() {
return(
<Provider style={styles.c} store={createStore(reducers)}>
<LoginForm/>
</Provider>
);
}
}
const styles = StyleSheet.create({
c: {
flex: 1
}
});
export default App;
Here's LoginForm.js:
import React, {Component} from 'react';
import {connect} from 'react-redux';
import {emailChanged} from 'TorusTeensApp/src/actions';
import {Text, StyleSheet, KeyboardAvoidingView, TextInput, TouchableOpacity} from 'react-native';
class LoginForm extends Component {
render() {
onEmailChange(text)
{
this.props.emailChanged(text);
}
return(
<KeyboardAvoidingView style={styles.container}>
<TextInput
style={styles.userInput}
onsubmitediting={() => this.passwordInput.focus()}
returnKeyType={"next"}
placeholder={"Email"}
label={"Email"}
keyboardType={"email-address"}
autoCorrect={false}
onChangeText={this.onEmailChange.bind(this)}
value={this.props.email}
/>
<TextInput
style={styles.userInput}
ref={(userInput) => this.passwordInput = userInput}
returnKeyType={"go"}
placeholder={"Password"}
label={"Password"}
secureTextEntry
/>
<TouchableOpacity style={styles.buttonContainer}>
<Text style={styles.buttonText}>Login</Text>
</TouchableOpacity>
<TouchableOpacity style={styles.buttonContainer}>
<Text style={styles.buttonText}>Create Account</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
);
}
}
const styles = StyleSheet.create({
container: {
padding: 20 // creates a gap from the bottom
},
userInput: {
marginBottom: 20,
backgroundColor: '#9b42f4',
height: 40
},
buttonContainer: {
backgroundColor: '#41bbf4',
paddingVertical: 10,
marginBottom: 20
},
buttonText: {
textAlign: 'center',
color: '#FFFFFF'
}
});
const mapStateToProps = state => {
return {
email: state.auth.email
};
};
export default connect(mapStateToProps, null, {emailChanged}) (LoginForm);
Here's index.js:
import {EMAIL_CHANGED} from './types';
export const emailChanged = (text) => {
return {
type: 'EMAIL_CHANGED',
payload: text
};
};
export default emailChanged();
Your connect is miswired
connect(mapStateToProps, null, {emailChanged}) (LoginForm);
It should be something like:
connect(mapStateToProps,
(dispatch) => ({emailChanged: (text) => dispatch(emailChanged(text))})
)(LoginForm);
so that your action actually gets dispatched
and as spotted by emed in comment:
export default emailChanged;
without parentheses.
You defined your callback inside your render() method and not inside the class body. Do it like this:
class LoginForm extends Component {
onEmailChange(text) {
this.props.emailChanged(text);
}
render() {
return(...);
}
}
Also you shouldn't bind methods inside your render() method. Do it in the constructor of your Component:
class LoginForm extends Component {
constructor(props) {
super(props);
this.onEmailChange.bind(this);
}
onEmailChange(text) {
// do something
}
// other methods
}
Or if you use babel and ES6, you can define your callback with an arrow function, then it will be automatically bound:
class LoginForm extends Component {
onEmailChange = text => {
// do something
};
// other methods
}
See also the react docs about autobinding.
Also your call to connect seems incorrect. If you want to dispatch the action emailChanged it has to look like this:
const mapStateToProps = state => {
return {
email: state.auth.email
};
};
const mapDispatchToProps = dispatch => {
// this put a function emailChanged into your props that will dispatch the correct action
emailChanged: text => dispatch(emailChanged(text))
};
const LoginFormContainer = connect(mapStateToProps, mapDispatchToProps)(LoginForm);
export default LoginFormContainer;
The third argument to connect needs to be a function that knows how to merge the output of mapStateToProps, mapDispatchToProps, and ownProps all into one object that is then used as props for your connected component. I think you're trying to pass that action to the mapDispatchToProps argument, which is the second argument not the third. So, based on what I think you're doing, you probably wanna change your connect line to look like this.
export default connect(mapStateToProps, {emailChanged}) (LoginForm);
Then, export the function from your actions file not the output of calling that function.
export default emailChanged;
Notice I removed the parentheses so it's not being called.
Then make the callback function a method on your class and bind it in the constructor.
constuctor(props) {
super(props);
this.onEmailChange = this.onEmailChange.bind(this);
}
onEmailChange(text) {
this.props.emailChanged(text);
}
Then update onChangeText on that element.
onChangeText={this.onEmailChange}

React-Redux: How do I populate a component's prop on load with data from an async call?

I have this autocomplete component that takes an array of terms as a dataSource prop. The data I want to feed in resides in a public API, and I've followed the tutorial here to get to the code below. But this tutorial (and many others out there) explain how to bind these actions to an event, whereas I want to populate this prop with data on page load. How would I go about doing that?
actions.js
import fetch from 'isomorphic-fetch';
export function loadSchools(termId) {
return {
type: 'LOAD_SCHOOLS',
termId
};
}
export function receiveSchools(termId, json) {
return {
type: 'RECEIVE_SCHOOLS',
termId,
schools: json.data.children.map(child => child.data), // ???
receivedAt: Date.now()
};
}
export function getSchools(termId) {
return function (dispatch) {
dispatch(loadSchools(termId));
return fetch('http://www.northwestern.edu/class-descriptions/4650/index-v2.json')
.then(response => {
if (response.status >= 400) {
throw new Error('Bad response from server');
}
return response.json();
})
.then(data => dispatch(receiveSchools(termId, data)));
};
}
reducers.js
const initialState = {
schoolsData: {
isFetching: false,
lastUpdated: 0,
schools: []
}
};
function schools(state = initialState, action) {
switch (action.type) {
case 'LOAD_SCHOOLS':
return {
...state,
isFetching: true
};
case 'RECEIVE_SCHOOLS':
return {
...state,
isFetching: false,
schools: action.schools,
lastUpdated: receivedAt
}
default:
return state;
}
}
export default schools;
Search.jsx
import React from 'react';
import AutoComplete from 'material-ui/AutoComplete';
export default class Search extends React.Component {
render() {
return (
<AutoComplete
hintText="Search for something."
dataSource={this.props.searchdata}
maxSearchResults={15}
filter={AutoComplete.caseInsensitiveFilter}
onNewRequest={}
/>
);
}
}
Search.propTypes = {
searchdata: React.PropTypes.array.isRequired,
onSelect: React.PropTypes.func
};
index.jsx
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { grey500, white, fullBlack } from 'material-ui/styles/colors';
import { fade } from 'material-ui/utils/colorManipulator';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import schools from './reducers/reducers';
import colors from './colors';
import NavBar from './components/NavBar.jsx';
import Serif from './components/Serif.jsx';
const store = createStore(schools, applyMiddleware(thunkMiddleware));
const muiTheme = getMuiTheme({
palette: {
primary1Color: colors.northwesternPurple,
primary2Color: colors.northwesternPurple120,
primary3Color: grey500,
accent1Color: colors.northwesternPurple30,
accent2Color: colors.richBlack10,
accent3Color: colors.richBlack50,
textColor: colors.richBlack80,
alternateTextColor: white,
canvasColor: white,
borderColor: colors.richBlack20,
disabledColor: fade(colors.richBlack80, 0.3),
pickerHeaderColor: colors.northwesternPurple,
clockCircleColor: fade(colors.richBlack80, 0.07),
shadowColor: fullBlack
}
});
class App extends React.Component {
render() {
return (
<Provider store={store}>
<MuiThemeProvider muiTheme={muiTheme}>
<div> {/* MuiThemeProvider requires stricly one child element */}
<NavBar />
<Serif /> {/* This component contains SearchContainer, which in turn contains Search */}
</div>
</MuiThemeProvider>
</Provider>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
You can render your Search component from another component, let's call it SearchContainer. SearchContainer is decorated by the connect function from react-redux that has as only role to dispatch the action to fetch the schools. SearchContainer doesn't render Search component until the school are fetched.
Here an example of what the code would look like. Here I assume you don't use react-redux.
First you have a small problem in your initial state in reducers.js. It should be:
const initialState = {
isFetching: false,
lastUpdated: 0,
schools: []
};
function schools(state = initialState, action) {
switch (action.type) {
case 'LOAD_SCHOOLS':
return {
...state,
isFetching: true
};
case 'RECEIVE_SCHOOLS':
return {
...state,
isFetching: false,
schools: action.schools,
lastUpdated: receivedAt
}
default:
return state;
}
}
SearchContainer.js
// ./containers/SearchContainer.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { loadSchools } from '../actions/actions'
import Search from '../components/Search';
class SearchContainer extends Component {
componentDidMount() {
this.props.loadSchools(this.props.termId);
},
render() {
const {
schools,
isFetching
} = this.props;
if (isFetching) {
return null;
}
return <Search schools={schools} />;
}
}
const mapStateToProps = (state) => ({
isFetching: state.isFetching,
schools: state.schools
});
const mapActionsToProps = (dispatch) => ({
loadSchools: (termId) => dispatch(loadSchools(termId)),
});
export default connect(mapStateToProps, mapActionsToProps)(SearchContainer);
In this way, at the first render, your Search component is not rendered. It is rendered, only after the schools are loaded.
You can dispatch the LOAD_SCHOOLS action from the componentDidMount lifecycle method (maybe in your Serif component but I can't see the code for that).
From the docs:
componentDidMount() is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering.
https://facebook.github.io/react/docs/react-component.html#componentdidmount

Categories

Resources