Redux is a predictable state container for JavaScript apps.
Used to simplify(lol) management of application state data in a React app.
A javascript object, usually with type
and payload
fields. Like:
{
type: 'ADD_REMINDER',
payload: { }
}
A function that returns an action. Like:
func() {
return ({
type: 'ADD_REMINDER',
payload: { }
});
}
A reducer takes the state(store) + an action, and returns a new state. It modifies the store based on an action.
Remember to never mutate the state directly. Instead, return a new instance of the state based on the current one.
- Create a
constants.js
file insrc
for storing types. Eg:
export const ADD_REMINDER = 'ADD_REMINDER';
- Create
actions
folder insrc
. Inside, createindex.js
as
import {ADD_REMINDER} from '../constants';
export const addReminder = (text) => {
const action = {
type: ADD_REMINDER,
text //same key-value name
}
return action;
}
- Create
reducers
folder insrc
. Inside, createindex.js
as
import {ADD_REMINDER} from '../constants';
//helper function
const reminder = (action) => {
return {
text: action.text,
id: Math.random()
}
}
const reminders = (state=[], action) => {
let reminders = null;
switch(action.type) {
case ADD_REMINDER:
reminders = [...state, reminder(action)]; //Spread operator
return reminders;
default:
return state;
}
}
export default reminders;
- Edit
index.js
to create the actual store and to set up the provider.
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import reducer from './reducers';
const store = createStore(reducer);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
- In the component file, just before exporting, define the functions
/*
These are needed:
import {bindActionCreators} from 'redux';
import {addReminder} from '../actions';
*/
function mapStateToProps(state) {
return {
reminders: state
}
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({addReminder}, dispatch);
}
- Modify the export statement as
export default connect(mapStateToProps, mapDispatchToProps)(App);
- Call the action creator from props when needed. In this case, on the click of a button.
handleClick(textFromUser) {
this.props.addReminder(textFromUser);
}
Or access the data
render() {
return(
...
<p>{this.props.reminders}</p>
...
);
}
If you have retained your sanity thus far, you have my respect.