Problems accessing state in React-native with redux app - reactjs

So I'm new to Redux and am having problems accessing the STATE. When I add the constructor() method into my Component (Welcome) I get a Cannot find module /Welcome error. I'll paste my code below as I'm really struggling!
I'm simply trying to print out the text state!
Components/Welcome/index.jsx
import React, { Text, View, StyleSheet } from 'react-native';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
const Welcome = React.createClass({ //() => (
constructor() {
super(props, context);
console.log("context", this.context);
}
render () {
// state = super(props);
// console.log(state);
return (
<View style={ styles.container }>
<Text style={ styles.welcome }>
React Native Redux Starter Kit
</Text>
<Text style={ styles.instructions }>
{ this.props.text }
</Text>
<Text style={ styles.instructions }>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
)
}
// );
});
containers/app.jsx:
import React, { Component } from 'react-native';
import { Provider } from 'react-redux';
import configureStore from 'configStore';
import ExNavigator from '#exponent/react-native-navigator';
import routes from 'routes';
export default class App extends Component{
/**
* Render
*
* #return {jsx} Render <Provider /> component
*/
render(){
return (
<Provider store={ configureStore() }>
<ExNavigator
initialRoute={ routes.getHomeRoute() }
style={{ flex: 1 }}
sceneStyle={{ paddingTop: 64 }} />
</Provider>
);
}
}
reducers/bar.jsx:
This is setting the state of text = "testssters". I'm trying to print this out in my component.
import Immutable from 'immutable';
import { BAR } from 'constants/ActionTypes';
const initialState = Immutable.fromJS({
text: "hi"
});
export default function bar(state = {
text: "testssters",
}, action)
{
switch(action.type) {
case BAR:
state = state;
break;
}
return state;
}
routes.jsx:
const routes = {};
/**
* Homepage
*
*/
// Shows the homepage (Welcome/index.js)
routes.getHomeRoute = () => ({
getSceneClass() {
return require('Welcome/').default;
},
getTitle() {
return 'Welcome';
}
});
configStore.jsx:
import { createStore, combineReducers, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import * as reducers from 'reducers/';
const createStoreWithMiddleware = compose(
applyMiddleware(thunk)
// Add remote-redux-devtools
)(createStore);
export default function configureStore() {
return createStoreWithMiddleware(combineReducers(reducers));
}

React.createClass() expects an object and not a function.
If you're using createClass(), in order to set an initial state use getInitialState.
const Welcome = React.createClass({
getInitialState: function () {
return { myState: 1 };
},
render: function () {}
});
If you want to use ES6 classes then the same would look like this
class Welcome extends React.Component {
constructor() {
super();
this.state = { myState: 1 };
}
render() {
}
}

Related

Redux - mapStateToProps not working (React-Native)

I am learning Redux and can't seem to get state to display in my home page. I get the error: 'undefined is not an object, evaluating this.props.titles.allTitles. The error is located in Home created by connect function' Here is the code, let me know if you need any other files. Thank you. I am adding more text to comply with stack overflow, thank you for your help.
home:
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import { connect } from 'react-redux'
class Home extends React.Component {
render() {
return (
<View>
<Text>Redux Test</Text>
<Button
title='+ new list'
onPress={() =>
this.props.navigation.navigate('New List')
}
/>
<Text>{this.props.titles.allTitles.length}</Text>
</View>
)
}
}
const mapStateToProps = (state) => {
const { titles } = state
return { titles }
};
export default connect(mapStateToProps) (Home);
```
reducer:
```
import { combineReducers } from 'redux';
const INITIAL_STATE = {
allTitles: []
};
const tagReducer = (state = INITIAL_STATE, action) => {
switch (action.type) {
case 'NEW_LIST':
return {
...state,
allTitles: [...state.allTitles, action.payload.title]
}
default:
return state;
}
};
const reducers = combineReducers({
tagReducer
})
export default reducers;
```
import React from 'react';
import { StyleSheet, Text, View, Button, TextInput } from 'react-native';
import { connect } from 'react-redux';
import { newList } from '../store/tagActions';
class List extends React.Component {
constructor(props){
super(props);
this.state = {
title: ''
}
}
render() {
return (
<View style={styles.container}>
<TextInput
style={styles.title}
placeholder='add Title..'
onChangeText={text => this.setState( {title: text} ) }
/>
<Button
title='done'
onPress={() => {
this.props.newList(this.state.title)
}
}
/>
<Text>{this.state.title}</Text>
</View>
)
}
}
const mapStateToProps = (state) => {
const { allTitles } = state
return { allTitles }
};
export default connect(mapStateToProps, { newList }) (List);
In your reducer, you have the following -
allTitles: [...state.allTitles, action.payload.title]
When you do, I don't see title in the redux state.
const mapStateToProps = (state) => {
const { titles } = state
return { titles }
};
You need to do
const mapStateToProps = (state) => {
const { allTitles } = state
return { allTitles }
};
Then do {this.props.allTitles.length} inside the render statement
Getting Redux setup can be pretty tricky in my opinion. After taking a look at your code I created a small React-Native project and setup Redux as closely as possibly to what you described in your question. Hopefully my answer helps. Please note that all three the files in my answer (App.js, Home.js, & titleReducer.js) are contained in the same directory.
App.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import titleReducer from './titleReducer';
// React-Redux
import {
createStore,
combineReducers,
} from 'redux';
import {
connect,
Provider
} from 'react-redux';
// Import Components (Screens)
import Home from './Home';
// Intialize Redux Store
const rootReducer = combineReducers({
titles: titleReducer
});
const store = createStore(rootReducer);
class App extends React.Component {
render() {
return (
<Provider store={store}>
<Home/>
</Provider>
)
}
}
export default App;
titleReducer.js
const initialState = {
allTitles: [],
};
const titleReducer = (state, action) => {
// check for state undefined to prevent
// redux from crashing app on load
if (typeof state === 'undefined') {
return {...initialState};
}
switch (action.type) {
case 'ADD_TITLE':
const newState = {...state};
const newTitle = action.payload;
newState.allTitles.push(newTitle);
return newState;
default:
return {...state};
}
// If none of the conditions above are true,
// simply return a copy of the current state
return {...state};
};
export default titleReducer;
Home.js
import React from 'react';
import { StyleSheet, Text, View, Button } from 'react-native';
import {
connect,
Provider
} from 'react-redux';
function randomTitle() {
return Math.random().toString();
}
class Home extends React.Component {
render() {
return (
<View>
<Text>Redux Test</Text>
<Button
title="Add Title"
onPress={ () => this.props.addTitle(randomTitle()) }/>
<Text>{this.props.titles.allTitles.length}</Text>
</View>
)
}
}
const mapDispatchToProps = dispatch => {
return {
addTitle: (payload) => dispatch({type: 'ADD_TITLE', payload: payload}),
};
};
const mapStateToProps = (state) => {
return {
titles: state.titles,
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Home);
I think you've forgot to define a store for your app. Go to your root class (app.js or something) and define your reducers to your store:
const store = createStore(tagReducer)
or if you have multiple reducers you can combine them in one line:
const store = createStore(combineReducers({
tag: tagReducer,
someOther: otherReducer
}));
Hope that it fixes your problem.

React native axios api calls with redux

I'm struggling to get a basic api call setup with redux and axios in React Native.
This is my reducer index.js
import { combineReducers } from 'redux'
import LibaryReducer from './LibraryReducer'
import ImportLibraryReducer from './ImportLibraryReducer'
let defaultState = {
card: null
}
const mainReducer = (state = defaultState, action) => {
if(action.type === "CHANGE_CARDS") {
return {
...state,
card: action.card
}
} else {
return {
...state
}
}
}
export default mainReducer
This is my action index.js
import axios from "axios"
export function loadCards(){
return(dispatch)=>{
return axios.get('http://localhost:4000/reports')
.then(response => {
dispatch(changeCards(response.data))
})
}
}
export function changeCards(cards) {
return{
type: "CHANGE_CARDS",
card: card
}
}
This is my app.js
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* #format
* #flow
*/
import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import MainPage from './components/MainPage'
import { Header } from "native-base"
import Card from './components/Card'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import thunk from 'redux-thunk'
import reducers from './reducers'
const store = createStore(reducers, applyMiddleware(thunk))
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<Provider store={store}>
<View>
<Header ><Text>hello</Text></Header>
<Card />
</View>
</Provider>
);
}
}
And, finally, this is where I'm trying to retrieve the data from the api call:
import React, { Component } from 'react';
import { Text, View } from 'react-native';
import {Collapse,CollapseHeader, CollapseBody, AccordionList} from 'accordion-collapse-react-native';
import { connect } from 'react-redux'
import * as actions from '../actions'
class Card extends Component {
render() {
const titleStyle = {
backgroundColor: '#edeeef',
fontWeight: "bold",
color: '#454647',
fontSize: 16,
left: 8,
fontFamily: 'Ionicons',
top: 10
}
const descMarkStyle = {
left: 8,
top: 4,
fontFamily: 'Ionicons',
color: '#454647',
fontSize: 16
}
console.log('in the render', this.props)
return (
<View>
<Collapse >
<CollapseHeader>
<View
style={{
backgroundColor: '#edeeef',
height: 38,
postion: 'absolute',
borderBottomWidth: .5,
borderBottomColor: '#black'
}}
>
<Text style={titleStyle}>
test
</Text>
</View>
</CollapseHeader>
<CollapseBody>
<Text style={descMarkStyle}>test</Text>
<Text style={descMarkStyle}>test</Text>
</CollapseBody>
</Collapse>
</View>
);
}
}
function mapStateToProps(state) {
return {
state
};
}
export default connect(mapStateToProps)(Card);
When I try to console log this.props in the component above, I get the default state of card: null without the api running: https://imgur.com/a/acB40KU
I'm new to redux, and I feel like there is something obvious that I'm missing.
You should trigger your action in the componentDidMount lifecycle method in your Card component. Also, you can destructure your actions in your imports and in your connect.
import { loadCards } from '../actions'
class Card extends Component {
componentDidMount() {
this.props.loadCards()
}
And in connect:
export default connect(mapStateToProps, { loadCards })(Card);
Also in the changeCards action:
card: cards
Here is how to set up axios with redux hooks and react-native in 4 steps:
source code: https://github.com/trackmystories/Redux-hooks-counter-app-with-axios.
Step 1:
create an actions.js file:
actions.js
export const TOTAL_COUNT = "TOTAL_COUNT";
export const totalCount = (data) => ({
type: TOTAL_COUNT,
data,
});
Step 2:
define and combine your reducers:
reducer.js
import { combineReducers } from "redux";
import { TOTAL_COUNT } from "./actions";
let dataState = { data: [] };
const total_counts = (state = dataState, action) => {
switch (action.type) {
case TOTAL_COUNT:
return { ...state, data: action.data };
default:
return state;
}
};
const counter = (state = 0, action) => {
switch (action.type) {
case "ADD":
return state + 1;
case "SUBTRACT":
return state - 1;
default:
return state;
}
};
const rootReducer = combineReducers({
counter,
total_counts,
});
export default rootReducer;
Step 3
create an axios get request and put request as defined in the example below and dispatch and get data.
With hooks you don't need to use connect mapStateToProps and dispatchStateToProps with redux hooks instead use { useDispatch, useSelector }.
We can pass the actions "ADD" and "SUBTRACT" inside of the button directly, without defining an action.js file.
CounterComponent.js
import React, { useEffect, useState } from "react";
import { StyleSheet, Text, View, ActivityIndicator } from "react-native";
import ActionButton from "./ActionButton";
import SubmitButton from "./SubmitButton";
import { useDispatch, useSelector } from "react-redux";
import axios from "axios";
import { totalCount } from "../actions";
export default function CounterComponent() {
const dispatch = useDispatch();
const [isFetching, setIsFetching] = useState(false);
const total_counts = useSelector((state) => state.total_counts);
const counter = useSelector((state) => state.counter);
const { data } = total_counts;
useEffect(() => getTotalCount(), []);
const getTotalCount = () => {
setIsFetching(true);
let url = "https://url.firebaseio.com<name>.json";
axios
.get(url)
.then((res) => res.data)
.then((data) => dispatch(totalCount(data)))
.catch((error) => alert(error.message))
.finally(() => setIsFetching(false));
};
const onSubmit = (counterState) => {
let url = "https://url.firebaseio.com<name>.json";
axios.put(url, counterState).then((response) => {
console.log(response);
});
};
return (
<View>
<ActionButton
onPress={() =>
dispatch({
type: "SUBTRACT",
})
}
title="subtract"
/>
<View>
{isFetching ? (
<ActivityIndicator />
) : (
<View>
<Text>
Current state:
{data.counter ? data.counter : counter}
</Text>
</View>
)}
</View>
<ActionButton
onPress={() =>
dispatch({
type: "ADD",
})
}
title="add"
/>
<SubmitButton
onPress={onSubmit({
counterState: counter,
})}
title="Submit"
/>
</View>
);
}
Step 4:
Lastly link your RootReducer to the createStore and pass it to the Provider.
import React from "react";
import { Text, View } from "react-native";
import { Provider } from "react-redux";
import { createStore } from "redux";
import CounterComponent from "./src/components/CounterComponent";
import rootReducer from "./src/reducer";
const store = createStore(rootReducer);
export default function App() {
return (
<View>
<Text>Counter example with Redux Hooks and Axios</Text>
<Provider store={store}>
<CounterComponent />
</Provider>
</View>
);
}

react HOC and losing reference to this

I'm trying to understand and use HOC with react and redux. I have the following setup. I will have multiple buttons using the hoc and passing in their own onClick. and would like to know:
a. Is this a good usage of the HOC pattern?
b. with this setup inside of the render function of FooterButton, this references DesignatedWorkerGlobalScope and iconHeigh, iconWidth, and iconColor inside HomeButton become either undefined or unexpected values.
Any advice would be appreciated.
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { getColors, getStylesheet} from "../../styles/StyleManager";
const FooterButtonWrapper = (FooterButtonWrapped, onClick) => {
return class FooterButton extends React.Component {
constructor(props) {
super(props);
this.state = {
Theme: getStylesheet(),
colors: getColors()
}
}
_onClick = () => {
onClick(this.props.dispatch);
}
render() {
const { Theme, colors } = this.state;
return(
<TouchableOpacity onPress={this._onClick}>
<FooterButtonWrapped iconWidth={15} iconHeight={15} iconColor={"white"}/>
</TouchableOpacity>
)
}
}
}
const mapStateToProps = (state, ownProps) => ({});
const composeFooterButton = compose(
connect(mapStateToProps),
FooterButtonWrapper
);
export default composeFooterButton;
and then a button that uses it:
import React from 'react';
import { View, Text } from 'react-native';
import { push as gotoRoute } from 'react-router-redux';
import { FooterButtonWrapper } from './';
import { Home } from '../../assets';
const HomeButton = ({iconHeight, iconWidth, iconColor}) => (
<View>
<Home width={ iconWidth } height={ iconHeight } color={ iconColor }/>
<View><Text>Home</Text></View>
</View>
);
const _onClick = dispatch => {
dispatch( gotoRoute( '/' ));
}
export default FooterButtonWrapper(HomeButton, _onClick);
It happens so, as you use
const composeFooterButton = compose(
connect(mapStateToProps),
FooterButtonWrapper
);
export default composeFooterButton;
for HOC function instead of Component.
Both compose and connect can wrap your Component.
So your HOC could be:
import React from 'react';
import { View, Text, TouchableOpacity } from 'react-native';
import { connect } from 'react-redux';
import { compose } from 'redux';
import { getColors, getStylesheet } from '../../styles/StyleManager';
export default function FooterButtonWrapper(FooterButtonWrapped, onClick) {
class FooterButton extends React.Component {
constructor(props) {
super(props);
this.state = {
Theme: getStylesheet(),
colors: getColors(),
};
}
_onClick = () => {
onClick(this.props.dispatch);
};
render() {
const { Theme, colors } = this.state;
return (
<TouchableOpacity onPress={this._onClick}>
<FooterButtonWrapped
iconWidth={15}
iconHeight={15}
iconColor={'white'}
/>
</TouchableOpacity>
);
}
}
const mapStateToProps = (state, ownProps) => ({});
return connect(mapStateToProps)(FooterButton);
}

React Native : Actions must be plain objects. Use Custom Middlewares for async operations

I know this is common issue and have been asked many times but i have gone through every solution but it didn't work.
I have been facing this error when i try to login from login form.
Here's code i'm attaching.
Login.js (View)
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { ScrollView, Text, TextInput, View, Button,StyleSheet,TouchableOpacity } from 'react-native';
import {loginRequest} from './../redux/actions/auth';
import {bindActionCreators} from 'redux';
class Login extends Component {
constructor (props) {
super(props);
this.state = {
username: '',
password: ''
};
}
userLogin (e) {
this.props.actions.loginRequest(this.state.username, this.state.password);
}
render () {
return (
<ScrollView style={{padding: 20,backgroundColor:'#ccc'}}>
<View style = {styles.container}>
<View style={{marginLeft:15}}>
<Text>Email</Text>
</View>
<TextInput
style = {styles.input}
underlineColorAndroid = "transparent"
placeholder = "Enter username"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText={(text) => this.setState({ username: text })}/>
<View style={{marginLeft:15}}>
<Text>Password</Text>
</View>
<TextInput
style = {styles.input}
underlineColorAndroid = "transparent"
placeholder = "Enter Password > 6 letters"
placeholderTextColor = "#9a73ef"
autoCapitalize = "none"
onChangeText={(text) => this.setState({ password: text })}/>
<TouchableOpacity
style = {styles.submitButton}
onPress={(e) => this.userLogin(e)}>
<Text style = {styles.submitButtonText}> Submit </Text>
</TouchableOpacity>
</View>
</ScrollView>
);
}
}
const mapStateToProps = (state, ownProps) => {
return {
isLoggedIn: state.auth.isLoggedIn
};
}
function mapDispatchToProps(dispatch){
return {
actions : bindActionCreators({
loginRequest
},dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Login);
auth action
In this action i am calling dispatch without any api call directly just for testing but even though that's not working.
export function loginRequest(username,password) {
alert("TEst"); // this alert comes
return function (dispatch) {
alert(`........Tracker......`); // execution doesn't reach here ,this alert doesn't com
if(username == 'admin' && password == 'admin'){
alert(`Login Success......`);
dispatch({
type : 'LOGIN_SUCCESS',
msg : 'Logged in successfully.'
});
resolve(true);
} else {
alert(`Login Failed......`);
dispatch({
type : 'LOGIN_FAIL',
msg : 'Please make sure you have entered valid credentials.'
})
reject(false);
}
};
}
This is my authReducer.js
export default function reducer(state = {},action){
if(action.type == 'LOGIN_SUCCESS'){
alert('login success');
return Object.assign({},state,{
isLoggedIn:true
})
} else if(action.type == 'LOGIN_FAIL'){
alert('login failed');
return Object.assign({},state,{
isLoggedIn:false
})
} else {
return state;
}
}
And entry point
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import {Provider} from 'react-redux';
import store from './redux';
import Application from './pages/Application';
export default class App extends Component{
render() {
return (
<Provider store={store}>
<Application />
</Provider>
);
}
}
I couldn't find any solution, can anyone help?
Because you are returning a function from your actions, you need to use middleware to handle returning functions instead of objects.
I am a fan of redux-thunk but there are plenty of other redux middlewares out there for this exact purpose.
You will need to update your store and configure it to use the middleware like so:
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';
export default(initialState) => {
return createStore(rootReducer, initialState, applyMiddleware(thunk));
}

Redux State in Component

trying to figure out how to pull Redux store state into my component from Redux. I've got mapStateToProps and "connect" wired up. However, when I click my button in "App" component, this.props doesn't have my Redux values in it.
// React and Redux Const
const { Component } = React;
const { render } = ReactDOM;
const { Provider, connect } = ReactRedux;
const {createStore, combineReducers, bindActionCreators } = Redux;
function tweetReducer(state=[],action) {
if(action.type === 'ADD_TWEET') {
return state.concat({ id: Date.now(), tweet: action.payload})
} else {
return state;
}
}
const rootReducer = combineReducers ({
state: (state = {}) => state,
tweets: tweetReducer
});
class App extends Component{
buttonClicked() {
store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
console.log(this.props)
}
render() {
return (
<div>
<h5>Hello from App</h5>
<button onClick={this.buttonClicked.bind(this)}>Button</button>
<div>-------------------</div>
<Display />
</div>
)
}
}
class Display extends Component {
render() {
return (
<div>
<h3>Tweets:</h3>
{this.props.tweets}
</div>
)
}
}
function mapStateToProps(state) {
console.log('mapping state to props')
return {
tweets: state.tweets
}
}
let store = createStore(rootReducer)
render (
<Provider store={store}>
<App />
</Provider>
, document.querySelector('#app')
);
connect(mapStateToProps)(App)
console.log(store.getState());
Looks like you've got a couple issues there.
First, it helps to understand that connect()(MyComponent) returns a new component that "wraps" around your "real" component. In your example, you're calling connect() after you've rendered <App />, and you aren't actually saving and using the component generated by connect(). What you need is something like:
let store = createStore(rootReducer)
const ConnectedApp = connect(mapStateToProps)(App);
render(
<Provider store={store}>
<ConnectedApp />
</Provider>
, document.querySelector('#app')
);
Second, part of the point of connecting a component is that it shouldn't actually reference the store directly. connect() can take a second parameter, known as mapDispatchToProps. If you don't supply a mapDispatch parameter, it will automatically give your component this.props.dispatch. So, your App component should look like this to start with:
class App extends Component{
buttonClicked(){
this.props.dispatch({type: 'ADD_TWEET', payload: 'This is my first tweet!'});
console.log(this.props)
}
That should be enough to get the App component receiving data from Redux and dispatching actions.
This is how you should proceed with getting store state in your component.
1) Create reducers folder and create a new file index.js
/* reducers/index.js */
import { combineReducers } from "redux";
import tweetReducer from "./tweetReducer";
const rootReducer = combineReducers({
tweets: tweetReducer
});
export default rootReducer;
/* reducers/tweetReducer.js */
function tweetReducer(state=[],action) {
switch(action.type) {
case 'ADD_TWEET':
return state.concat({ id: Date.now(), tweet: action.payload});
default:
return state;
}
}
/* components/App.js */
import React, { Component } from 'react';
import { connect } from 'react-redux';
class App extends Component {
buttonClicked() {
this.props.store.dispatch({type: 'ADD_TWEET', payload: 'This is my first
tweet!'});
console.log(this.props)
}
render() {
return (
<div>
<h5>Hello from App</h5>
<button onClick={this.buttonClicked.bind(this)}>Button</button>
<div>-------------------</div>
<Display />
</div>
)
}
}
function mapStateToProps(state) {
console.log('mapping state to props')
return {
tweets: state.tweets
}
}
export default connect(mapStateToProps)(App);
/* components/Display.js */
import React, { Component } from 'react';
export default class Display extends Component {
render() {
return (
<div>
<h3>Tweets:</h3>
{this.props.tweets}
</div>
)
}
}
/*Main.js */
import React, { Component } from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { store } from "./store";
render(
<Provider store={store}>
<App store={store} />
</Provider>,
document.querySelector('#app')
);
/* store/index.js */
import { createStore, applyMiddleware, compose } from "redux";
import reducers from "../reducers";
const store = createStore(
reducers,
composeEnhancers(applyMiddleware())
);
export { store };

Resources