React: Using a redux export connect from other components - javascript

I'm writing a mobile app with React Native. I have two js files as following:
Error.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getTranslate } from 'react-localize-redux';
function mapStateToProps(state) {
return {
t: getTranslate(state.locale)
};
}
export default connect(
mapStateToProps
)(
({ t }) => ({
e001: t('wrong_format'),
e002: t('invalid_email'),
})
);
SignIn.js
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getTranslate } from 'react-localize-redux';
import { Field, reduxForm } from 'redux-form';
import Error from './Error';
const validate = (values) => {
console.log('error: ', Error);
// Process validate redux-form with messages from Error.js
};
class SignIn extends Component {
// Process login form with redux-form
}
function mapStateToProps(state) {
return {
t: getTranslate(state.locale),
};
}
const SignInForm = {
form: 'SignIn',
validate,
};
export default connect(
mapStateToProps
)(
reduxForm(SignInForm)(
SignIn
)
);
How can I use the data that exported from Error.js in SignIn.js? (e.g. values of 'e001', 'e002')
Example from validate function (in SignIn.js) I wanna show the value of code "e001" from Error.js.
For more detail, my idea is collect all error messages from language file (using react-localize-redux) into Error.js, then from validate functions of redux-form, i can show those messages easier.

Its look like you want Error.js as a helper file.But you are implemented it as react-redux container.
If you implementing it as react-redux container then necessarily it will call every time whenever store will change.
Instead simply export it.
import { getTranslate } from 'react-localize-redux';
const format = ({
e001: getTranslate('wrong_format'),
e002: getTranslate('invalid_email'),
})
export default format;
Called it as once imported
console.log(format.e001);

Related

React-Redux connect isn't getting store from Provider

Im using Redux with React Native to manage state. I believe that I've successfully set up the store and Provider. I can use store.getState() and store.dispatch(action()) from any component successfully, however, the react-redux connect function is not allowing me to access the store from child components. Can you find anything wrong with my code below?
Login.js - This child component I'm testing won't access redux store with react-redux connect.
import React, {Component} from 'react';
import actions from '../../redux/actions';
import {connect} from 'react-redux';
const mapStateToProps = state => {
// To test if this function fires, which it is not
console.log('login state mapping through redux');
return {
state: state,
};
};
const dispatchToProps = dispatch => {
return {
userRecieved: (user) => dispatch(actions.userRecieved(user)),
};
};
export class Login extends Component {
constructor(){
super();
this.state = {
credentials: {
email: '',
password: '',
},
};
}
componentDidMount(){
// This will show whether redux is connected
console.log(this.props.state);
this.props.userRecieved('TEST USER');
}
render() {
return ( <Text>{this.props.state}</Text> );
}
}
export default connect(mapStateToProps, dispatchToProps)(Login);
App.js
import React, {Component} from 'react';
import YEET from './src/YEET.js';
import store from './src/redux/stores/index';
import {Provider} from 'react-redux';
export default class App extends Component {
render() {
return (
<Provider store={store}>
<YEET />
</Provider>
);
}
}
My Redux Files:
store.js
import { combineReducers, createStore} from 'redux';
import accountReducer from '../reducers/accountReducer';
import postReducer from '../reducers/postReducer';
const initialState = {};
const reducers = combineReducers({
account: accountReducer,
post: postReducer,
});
const store = createStore(reducers, initialState);
export default store;
actions.js
import constants from '../constants';
var userRecieved = user => ({
type: constants.USER_RECIEVED,
data: user,
});
export default {
userRecieved,
};
accountReducer.js
import constants from '../constants';
var initialState = {
user: {
photos: [],
},
};
export default (state = initialState, action ) => {
let newState = Object.assign({}, state);
switch (action.type) {
case constants.USER_RECIEVED:
const user = {
id: action.data.uid,
// photos: action.data,
};
console.log(action);
newState.user = user;
return newState;
default:
return state;
}
};
From what I see, the only reason could be that you're importing the unconnected component.
When you import the Login component, make sure that you import the default export instead of the named export.
So, wherever you import the Login component, do it like this:
import Login from 'your-login-component-location/Login'
instead of
import { Login } from 'your-login-component-location/Login'
The second one is a named export, which will return the Login class directly.
The first one is the default export, which will return the connected component.

Why I can't apply redux's connect with material-ui withStyles?

I'm trying to add withStyles() hook from material-ui in the redux container-component with connect() function via { compose } function from 'recompose' and get this error from recompose package:
TypeError: Function.prototype.apply was called on #, which is a object and not a function
I ask for any help, I have already spent too much time on this
import { withStyles } from '#material-ui/core/styles';
import { styles } from './styles';
import { compose } from 'recompose';
import { connect } from 'react-redux';
...
function mapStateToProps(state) {
return {
someVal: state.someVal,
}
}
function mapDispatchToProps(dispatch) {
return ({
changeVal: () => {dispatch('CHANGE_VAL')}
})
}
export default compose(
withStyles(styles),
connect(mapStateToProps, mapDispatchToProps)(App)
);
//if i do:
export default connect(mapStateToProps,mapDispatchToProps)(App)
//or:
export default withStyles(styles)(App)
//it's work. (just to clarify)
connect and withStyles are both HOC
a higher-order component is a function that takes a component and returns a new component.
So you need to wrap App inside withStyles and connect
export default connect(mapStateToProps,mapDispatchToProps)(withStyles(styles)(App))

React Redux Life Cycle Confussion

I have been reading several documents and watching videos regarding React Redux, but since all of them are different I wasn't able to apply that knowledge to some real project.
I will try to enumarate the process in order to use React Redux together.
Directory Structuring
project
src
components
User
index.js (Container component)
page.js (Presentational component)
actions
users.js
index.js (exports actionCreators combination)
reducers
users.js
index.js (exports reducer combination with combineReducers
constants
actionTypes.js
services
users.js
index.js
store.js
public
index.html
Redux Setup
We create constants in project/src/constants/actionTypes.js:
export const CREATE_USER = 'CREATE_USER';
export const DELETE_USER = 'DELETE_USER';
export const UPDATE_USER = 'UPDATE_USER';
We create actionCreators en project/src/actions/users.js y luego se combinan en project/src/actions/index.js:
users.js
import { CREATE_USER } from '../constants/actionTypes';
export default function createUser(user) {
type: CREATE_USER,
user
}
index.js
import { createUser } from './users';
export default {
createUser
}
We create reducers in project/src/reducers/users.js and they are combined in project/src/reducers/index.js using combineReducers():
users.js
import { CREATE_USER, UPDATE_USER, DELETE_USER } from '../constants/actionTypes';
import { createUser } from '../services/users';
const initialState = {
name: '',
password: '',
email: ''
}
export default function users(state = initialState, action) {
switch (action.type) {
case CREATE_USER:
state = createUser(action.user);
return state;
}
}
index.js
import users from './users';
export default combineReducers({
users
})
We create store in project/src/store.js:
import { createStore } from 'redux';
import reducers from './reducers';
export const store = createStore(reducers);
React Redux Setup
We wrap component application <Provider> in project/src/index.js:
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { store } from './store';
const Root = () => (
`
<Provider store={store}>
<App />
</Provider>
`
)
ReactDOM.render(Root, document.getElementById('root');
We transform component state to properties with mapStateToProps in project/src/components/User/index.js:
import React, { Component } from 'react';
import { createUser } from '../../actions/users';
import Page from './page';
class User extends Component {
render() {
return <Page users={this.props.users} />
}
}
const mapStateToProps = state => ({
users: this.props.users
// what is mapped here?
});
const mapDispatchToProops = dispatch => ({
// what about here?
});
export default connect(mapStateToProps, mapDispatchToProps)(User);
So, the question would be, is this React-Redux cycle well formed? What is missing or wrong?
Yes, the folder structure works well. As for the "fetch" or "service" functionality you're talking about, I'll give you an example of what actions and reducers both should, in a basic example, do.
So if you're working with a backend which you're "fetching" anything from, I'd recommend adding that functionality in the action, not the reducer:
import { USERS_FETCHED } from '../constants/actionTypes';
import { baseUrl } from "../constants/baseUrl";
const usersFetched = users => ( { // action to dispatch
type: USERS_FETCHED,
users,
} );
export const fetchUsers = () => ( dispatch ) => { // export for mapDispatchToProps
request( `${ baseUrl }/users` )
.then( response => {
dispatch( usersFetched( response.body ) ); // dispatch the action to reducer
} )
.catch( console.error );
}; // in your case you import createUser(), but it works either way
Now the action is concerned with functionality, in contrast the reducer is only concerned with managing the Redux state:
import { USERS_FETCHED } from "../constants/actionTypes";
export default ( state = null, action = {} ) => {
switch ( action.type ) {
case USERS_FETCHED:
return action.users;
default:
return state;
}
};
Functionality in the reducer is fine, but it should only be concerned with managing state. You can imagine how cluttered the code could get if you start fetching any data here, not to mention problems with asynchronicity. Of course, this is just one way to do it, but it works solidly. Hope this helps you in some way.

Print value from props, which is delivered to the component from redux by mapStateToProps

Problem:
I can't display the value from the state of redux, which is delivered by mapStateToProps function to the component.
Project structure:
Create-react-app CLi application built the project.
Inside of the src/ I have the following code structure
Necessary code:
The main page which we are interacting with looks like this:
Underneath it is planned to post the result of the clicking on the buttons.
So how do I bind the redux state and actions to those two components: Calculator and ResultLine?
Let me show the index.js code, where I create the store:
import React from "react";
import ReactDOM from "react-dom";
import { Provider } from "react-redux";
import { createStore } from "redux";
import reducers from './reducers/';
import App from './components/App';
ReactDOM.render(
<Provider store={createStore(reducers)}>
<App />
</Provider>,
document.getElementById("root")
);
There are only three actions:
import {CALCULATE, ERASE, PUT_SYMBOL} from "./types";
export const putSymbol = (symbol) => {
return {
type: PUT_SYMBOL,
payload: symbol
}
};
export const calculate = () => {
return {
type: CALCULATE
}
};
export const erase = () => {
return {
type: ERASE
}
};
And in the App.js I pass reducers, which are binded to those actions to the Calculator component:
import React, {Component} from 'react';
import Calculator from './Calculator';
import ResultLine from "./ResultLine";
import {calculate, erase, putSymbol} from "../actions/index";
import {connect} from "react-redux";
class App extends Component {
render() {
return (
<div>
<Calculator
onSymbolClick={this.props.onSymbolClick}
onEqualsClick={this.props.onEqualsClick}
onEraseClick={this.props.onEraseClick}/>
<br/>
<ResultLine result={this.props.result}/>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('mapState', state.calc.line);
return {
result: state.line
}
};
const mapDispatchToProps = {
onSymbolClick: putSymbol,
onEqualsClick: calculate,
onEraseClick: erase
};
export default connect(mapStateToProps, mapDispatchToProps)(App);
And that works fine. Whenever I click the button the state changes, and I observe it in the console log, called in mapStateToProps function.
So I expect, that I can deliver result prop to the Result line easily, and I pass it into the ResultLine component as a parameter. So, let's look at that element:
import React from 'react';
const ResultLine = ({result}) => {
return (
<p>{result}</p>
);
};
export default ResultLine;
And I can see no changes in a result line. Maybe, something wrong with the React/Redux lifecycle management and ResultLine component just does not update on changes in state?
There's an error on mapStateToProps.
Instead of:
const mapStateToProps = (state) => {
return {
result: state.line
}
}
Please use:
const mapStateToProps = (state) => {
return {
result: state.calc.line // calc was missing here
}
}

Code transformer AST to JS

I'm trying to write js code transformer. I need to parse JS into an AST do some modifications, for example add a new import declaration, and generate JS code back.
Currently I have some troubles with generating JS code. Decorators appear in a wrong place and generator remove brackets around JSX.
I'm new in this area, so probably, I miss some options while transforming/generating code.
Source code:
// Core
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from '../../actions/navigation';
const mapStateToProps = ({ navigation }) => ({ // eslint-disable-line arrow-body-style
menuStatus: navigation.get('menuStatus')
});
const mapDispatchToProps = (dispatch) => ({ // eslint-disable-line arrow-body-style
actions: bindActionCreators({ ...actions }, dispatch)
});
#connect(mapStateToProps, mapDispatchToProps)
export default class Home extends Component {
render () {
return (
<section>
<h1>Home container!</h1>
</section>
);
}
}
Parsed/generated code:
// Core
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { actions } from '../../actions/navigation';
const mapStateToProps = ({ navigation }) => ({ // eslint-disable-line arrow-body-style
menuStatus: navigation.get('menuStatus')
});
const mapDispatchToProps = dispatch => ({ // eslint-disable-line arrow-body-style
actions: bindActionCreators({ ...actions }, dispatch)
});
export default #connect(mapStateToProps, mapDispatchToProps)
class Home extends Component {
render() {
return <section>
<h1>Home container!</h1>
</section>;
}
}
Demo repository
It is a Babel bug: https://github.com/babel/babel/issues/4585
If the expectation is that you want to generate code that could be saved back to the filesystem, you are likely better off looking at JSCodeShift since it is targetted at preserving formatting while manipulating code, while Babel has only some interest in existing formatting.

Categories