Sunday, February 3, 2019

Redux - Reducers

Reducers specify how the application's state changes in response to actions sent to the store. Remember that actions only describe what happened, but don't describe how the application's state changes.

In Redux, all the application state is stored as a single object. It's a good idea to think of its shape before writing any code. What's the minimal representation of your app's state as an object?

The reducer is a pure function that takes the previous state and an action, and returns the next state.

(previousState, action) => newState

Below are the things that one should not do inside a reducer.

1. Mutate its arguments;
2. Perform side effects like API calls and routing transitions;
3. Call non-pure functions, e.g. Date.now() or Math.random().

We'll start by specifying the initial state. Redux will call our reducer with an undefined state for the first time. This is our chance to return the initial state of our app:

import { VisibilityFilters } from './actions'

const initialState = {
  visibilityFilter: VisibilityFilters.SHOW_ALL,
  todos: []
}

function todoApp(state, action) {
  if (typeof state === 'undefined') {
    return initialState
  }

  // For now, don't handle any actions
  // and just return the state given to us.
  return state
}

This can be written more neatly by using ES6 syntax


function todoApp(state = initialState, action) {
  // For now, don't handle any actions
  // and just return the state given to us.
  return state
}

Since overall state is coming in the response, it is the reducers responsibly to not change anything in the original state. The redux framework will mix it
That being said, below is the code that returns the state but just changes the visibilityFilter value.

function todoApp(state = initialState, action) {
  switch (action.type) {
    case SET_VISIBILITY_FILTER:
      return Object.assign({}, state, {
        visibilityFilter: action.filter
      })
    default:
      return state
  }
}

Below are two important points regarding this


1)    We don't mutate the state. We create a copy with Object.assign(). Object.assign(state, { visibilityFilter: action.filter }) is also wrong: it will mutate the first argument. You must supply an empty object as the first parameter. You can also enable the object spread operator proposal to write { ...state, ...newState } instead.

2)    We return the previous state in the default case. It's important to return the previous state for any unknown action.



References:
https://redux.js.org/basics/reducers

React-Native : pass data from ui layer to the server using redux

Lets say a login form and now we need to login the user. Below are the steps involved if we are doing this using redux

In the services file, add a method like below

async function

So it all begins with creating an action in the action class. For e.g the action could be like this below.
So essentially, this function returns a method that returns a JSON object that contains the key value pairs containing necessary
Info for login

SignInActions.js

Export const performUserSignIn = (username, password) => ({
type : ActionTypes.SIGNIN_USER,
username : username,
password : password;})

All these are info for reducers. Type indicates the action type. ActionType is an import like this below

Import ActionTypes from ./actionTypes.js

Now in the ui file, this action can be mapped to property like this below

Import SignInActions from ./SignInActions.js

Function mapDispatchToProps(){
   loginUser : SignInActions. performUserSignIn
}

This mapped dispatch can be called like this

this.props.loginUser("test","password1");

Now we need to have a reducer which will be like below


References:

Redux - Actions

Actions are payloads of information that send data from your application to your store. They are the only source of information for the store. You send them to the store using store.dispatch().

Actions are plain JavaScript objects. Actions must have a type property that indicates the type of action being performed. Types should typically be defined as string constants. Once your app is large enough, you may want to move them into a separate module.


For e.g.

const ADD_TODO = 'ADD_TODO';

{
   type: ADD_TODO,
   Text: 'Sample data'
}

Other than type, the structure of an action object is really up to the developer.

Action Creators

Action creators are exactly that—functions that create actions
For e.g.

function addTodo(text) {
return {type:ADD_TODO,text}
}

to actually initiate a dispatch, pass the result to the dispatch() function:
dispatch(addTodo(text))

We can also bound action creator that automatically dispatches:

const boundAddTodo = text => dispatch(addTodo(text))
const boundCompleteTodo = index => dispatch(completeTodo(index))

The dispatch() function can be accessed directly from the store as store.dispatch(), but more likely you'll access it using a helper like react-redux's connect(). You can use bindActionCreators() to automatically bind many action creators to a dispatch() function.


References:
https://redux.js.org/basics/actions