Implementation of redux inside any react.js or react-native application,
- we will create an instance of the redux store.
- We are going to create a provider tag from react redux library
- Then render that provider tag passing in the store as a prop, then any child component to this provider tag will have access to this store through the context system inside of react.
- import { Provider } from ‘react-redux’; // In main.js
- to create a store create one in a separate folder.
// store/index.js
import { createStore, compose, applyMiddleware } from ‘redux’;
import thunk from ‘redux-thunk’;
const store = createStore({
reducers,
{}, // default state of the application
compose(
applyMiddleware(thunk)
)
})
export default store;
- create default or dummy reducer by creating a new folder reducers/
- create index.js and create a dummy reducer to get started.
import { combineReducers } from 'redux';
export default combineReducers({
temp: () => {return {}}
})
temp state and always returns an object. reducer must return an object or a string or a number and never return undefined.
- import reducers in the store/index.js
import reducers from '../reducers';
- import the store in the main.js
import store from './store';
<Provider store={store}>
</Provider>
now every single component inside of our application will have access to the store by using the connect helper from the react-redux library.
Action creater.
create a action type by creating a new file in types.js
in the actions folder.
// types.js
export const TYPE_1 = 'type_1';
Now create the action file that is going to house our action creater.
actions/ index.js type_1.js types.js
// in type_1.js
import {
TYPE_1
} from './types';
export const type1_action = (dispatch) => {
data = '2' // get this data from where ever you want, an API maybe?
// Dipatch the function
dispatch({
type: TYPE_1,
payload: data
})
}
In the index.js import all the action creaters.
export * from './type_1';
Now, let's wire it up with the class and see if this works. open a file where you want to use this action.
screens/TestScreen.js
//TestScreen.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
class TestScreen extends Component {
render(){
return (
<View>
<Text>
Bhwaahahahaa
</Text>
</View>
);
}
}
export default TestScreen;
This is the basic boilerplate not let's add connect helper.
import { connect } from 'react-redux';
// connect helper takes 2 set of parentheses.
// connect(mapStateToProps or null, actions )(Component);
import * as actions from '../actions';
export default connect(null, actions)(TestScreen);
new we can call our action creater by saying
this.props.type1_action();