Tuesday, December 31, 2019

Map state to props, map dispatch to props . React JS

Various samples of MapStateToProps and mapDispatchToProps

Example1:

function mapDispatchToProps(dispatch) {
    return({
        sendTheAlert: () => {dispatch(ALERT_ACTION)}
    })
}

In the below example, the fancyInfo is kind of local variable which is taking values the sum of

function mapStateToProps(state} {
    return({fancyInfo: "Fancy this:" + state.currentFunnyString})
}


The component in the pattern, FancyAlerter, which does the rendering doesn't need to know about any of that stuff: it gets its method to call at onClick of the button, via its props.

And ... mapDispatchToProps was the useful means that redux provides to let the container easily pass that function into the wrapped component on its props.

In short,

mapStateToProps() is a utility which helps your component get updated state(which is updated by some other components),
mapDispatchToProps() is a utility which will help your component to fire an action event (dispatching action which may cause change of application state)


Example 2:

In the below case, the concept is, whenever the state change happens, it comes into the mapStateToProps. And then the todos: is get updated based on a new operation such as filtration done inside the getVisibleTodos function.

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

The below mapDispatch to props, someone can call onTodoClick from the ui, and it will dispatch the toggleTodo with the id given.
For e.g. like the below

        key={todo.id}
        {...todo}
        onClick={() => onTodoClick(todo.id)}
      />


const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}


No comments:

Post a Comment