InterviewSolution
| 1. |
Explain the flow in a React-Redux app? |
|
Answer» As on Redux site “Redux is a predictable state container for JavaScript apps.” Redux can be used separately, but it gained much popularity because it was able to solve the state problem in a REACT app. In React to pass DATA(or state) between COMPONENT, we use props to be passed from Parent to Children. If the data needs to be passed to Components 5 level deep then it has to just have to pass through 4 Components, which doesn’t require it. Passing data from Child to Parent is also a problem, and we need to use the Callback function. This gets complicated soon in a large application. So, to solve this issue we maintain state, which is the main data of the application in a CENTRAL location. It can be accessed by any Components which ask for it. Let see the complete flow. The Container is a file that corresponds directly to a single component. It have two functions called ‘mapDispatchToProps’ and ‘mapStateToProps’. The Action Creator: In this file, you will write the functions that dispatch an action. It performs some action, like an API call using axios. When we get the response back from it, we will dispatch an Object with “type” and “data” as { type: GET_INDIA_DATA, indPopData: response.data } The Reducer hears: an action, and can now generate a new state BASED on what the action wants it to do. Note the state never actually changes in Redux, but instead, the reducer generates a new state which is a copy of the old state. In the code below we don’t mutate the state but create a new state by Object destructuring. const initialState = { indPopData: [], }; const dataReducer = (state = initialState, action) => { let newState; switch (action.type) { case types.GET_INDIA_DATA: newState = { ...state, indPopData: action.indPopData }; break; default: newState = state; } return newState; };Back to Container: the result is received by “mapStateToProps”. It can be accessed as a prop ie “this.props.indPopData” in this case. Here, we are also data massaging the data in componentWillReceiveProps and storing it in local state variables “indPieData” and “indPopTotal” After that it is rendered in the component using “this.state.indPopTotal” and “this.state.indPieData” ... componentWillReceiveProps(nextProps) { if (this.props.indPopData !== nextProps.indPopData) { this.setState({ indPieData: nextProps.indPopData.map(item => {return {name: item.age, value:item.total}})), indPopTotal: nextProps.indPopData.map(item => {return {name: item.age, value:item.total}}); } } ... render() { return ( <Fragment> {this.state.indPopTotal && <p style={totalText}> India - {this.state.indPopTotal} </p>} {this.state.indPieData && <PopPieChart popPieData={this.state.indPieData} />} </Fragment> ) } const mapStateToProps = ({ dataReducer }) => ({ indPopData: dataReducer.indPopData, ... }); |
|