newUserActions.js

doing some actions and dispatching action events

 

 

const actNewUser = postData => dispatch => {

  let usercreating = postData;

  axios

    .post(page.pathpostData)

    .then(res => {

 

      dispatch({

        type: t.ADD_ALERT,

        payload: { alertFor: 'newUser'alertType: 'success'alertMsg: msg }

      });

 

     

    })

    .catch(err => {

      dispatch({

        type: t.ADD_ALERT,

        payload: {

          alertFor: 'newUser',

          alertType: 'danger',

          alertMsg: newAlertMsg

        }

      });

 

    })

    ;

 

};

 

export { actNewUser };

 

 

 

 

 

 


 

RouteUser/user.js

 

Component that has user interaction calls some action and waitching for return status and notified once received

 

Connecting the dots : action and states

 

 

 

import { actNewUser } from 'actions/newUserActions';


class PageUser extends Component {

  

  onValidate = e => {

 

     this.props.actNewUser({

        username,

        firstname,

        lastname,

        email,

        authorities

      });

    }

  }

 

const mapStateToProps = state => ({

  status: state.newUser.status,

  alertMe: state.notification.alertMe

});

 

export default connect(

  mapStateToProps,

  { actNewUser }

)(PageUser);

 

 

 

 

 

 


 

 

Reducers/newUserReducer.js 

data and changes in data

 

 

const INIT_STATE = {

  status: null

};

 

export default (state = INIT_STATEaction=> {

 

  switch (action.type) {

 

    case 'NEW_USER' : {

      return {

        ...state,

        status: action.status,        

 

      };

    }

 

    defaultreturn state;

 

  }

};

 

 

 

allReducers.js

combining / collating all the data changes by combining all the reducers

 

import { combineReducers } from 'redux';

 

import newUserReducer from './newUserReducer';

 

const reducers = combineReducers({

 

  newUser: newUserReducer,

 

});

 

export default reducers;

 

 

stores.js

 

all the reducers are stored in single store

 

 

 

import reducers from './reducers/index';

 

function configureStore(initialState) {

 

  const store = createStore(

    reducers,

    initialState,

    compose(applyMiddleware(...middlewares))

  );

 

  return store;

}

 

export { configureStore };

 

 

 


 

 

MainApp.js

 

Subscribing to the store

It has collection of application pages for view

 

 

 

 

import React from 'react';

import { Provider } from 'react-redux';

import { configureStore } from './store';

const store = configureStore();

 

class MainApp extends React.Component {

  render() {

    return (

      <Provider store={store}>

        <ConnectedRouter history={history}>

          <Switch>

            <Route path='/' component={App} />

          </Switch>

        </ConnectedRouter>

      </Provider>

    );

  }

}

 

export default MainApp;

 


 

Sample for mapDispatchToProps

 

 

class UserList extends Component {

  renderList() {

    return this.props.users.map(user => {

      return (

        <li key={user.id} onClick={() => this.props.selectUser(user)}>

          {user.first} {user.last}

        </li>

      )

    })

  }

  render() {

    return <ul>{this.renderList()}</ul>

  }

}

function mapStateToProps(state) {

  return {

    users: state.users,

  }

}

function mapDispatchToProps(dispatch) {

  return bindActionCreators({ selectUser: selectUser }, dispatch)

}

export default connect(

  mapStateToProps,

  mapDispatchToProps,

)(UserList)

 

 

 

 

 

 

Image result for redux lifecycle

 

 

 

Image result for redux lifecycle

 

 

 


 

 

 

 


 

 


 

 


 

 

 


 

 

 

 


 

 

 


 

 


 

 


 

 

 

 

Image result for redux lifecycle

 

 

 

 

Related image

 

 

 

 

 

export default connect(mapStateToProps)(MyComponent);

 

 

Think of connect() as the glue or interface between the component and the store. Any changes to the state will be reflected in the component because it is “connected” to mapStateToProps and that information is now made available to the component through a prop.

 

mapDispatchToProps

 

const mapDispatchToProps = () => {

     return {

          addThing: addThing,

          doAnotherThing: doAnotherThing

     }

}

 

As implied in its name, this function directs the dispatching or sending of an action by pointing it to an action creator. For example:

 

The action creator is made available to the component as a prop, which is usually tied to an event handler function contained in the component:

 

handleOnClick() {

    this.props.addThing();

};

 

We also want the send that returned action to the store.

 

import { bindActionCreators } from 'redux';

...

const mapDispatchToProps = (dispatch=> {

  return bindActionCreators({

         addThing: addThing,

         doAnotherThing: doAnotherThing

         }, dispatch);

};

The bindActionCreators() function accepts the action creator and the store’s dispatch function as arguments, and returns a dispatch function that uses the return value of the action creator as its arguments.

 

Tying this all together is the connect() function, in which we pass mapDispatchToProps as a second argument. For example:

 

export default connect(mapStateToPropsmapDispatchToProps)(MyComponent);

 

which will export a component that can both get the current state from the store, and dispatch an action to the store to trigger and update to the state.

 

 

https://www.sohamkamani.com/blog/2017/03/31/react-redux-connect-explained/

 

import { connect } from 'react-redux'
 
const TodoItem = ({ todo, destroyTodo }) => {
  return (
    <div>
      {todo.text}
      <span onClick={destroyTodo}> x </span>
    </div>
  )
}
 
const mapStateToProps = state => {
  return {
    todo: state.todos[0]
  }
}
 
const mapDispatchToProps = dispatch => {
  return {
    destroyTodo: () =>
      dispatch({
        type: 'DESTROY_TODO'
      })
  }
}
 
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoItem)

 

 

 

 

  1. Components are given callback functions as props, which they call when a UI event happens
  2. Those callbacks create and dispatch actions based on the event
  3. Reducers process the actions, computing the new state
  4. The new state of the whole application goes into a single store.
  5. Components receive the new state as props and re-render themselves where needed.

 

 

Common mistakes in redux

 

 

function updateNestedState(stateaction) {

  let nestedState = state.nestedState

  // ERROR: this directly modifies the existing object reference - don't do this!

  nestedState.nestedField = action.data

 

  return {

    ...state,

    nestedState

  }

}

 

function updateNestedState(stateaction) {

  // Problem: this only does a shallow copy!

  let newState = { ...state }

 

  // ERROR: nestedState is still the same object!

  newState.nestedState.nestedField = action.data

 

  return newState

}