store
dispatched/run methods which trigger reducers)store is where the application state residesreducers and middlware needed available and used globallyreducers hold and manage a small piece of the larger state
products, categories, and cartslet initialState = { customerId: null, items: [] };
const myReducer = (state = initialState, action) => {
let { type, payload } = action;
switch (type) {
case 'INITIALIZE':
return {customerId: payload.id};
case 'ADD_ITEM':
return { items: [...items, payload.item] };
case 'CLEAR':
return initialState;
default:
return state;
}
};
dispatches an action with a payloadaction creator sends a payload and an action to perform// actions.js
const newCart = customer => {
return {
type: 'INITIALIZE',
payload: customer,
};
};
store ties it all togetherimport { createStore, combineReducers, applyMiddleware } from 'redux';
import cartReducer from './reducers/cart.js';
let reducers = combineReducers({
cart: cartReducer,
});
export default () => createStore(reducers);
connect() to attach to the store and get methods, but it needs to be provided for the app to see itimport React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import './style.scss';
import App from './components/app';
import createStore from './store';
const store = createStore();
class Main extends React.Component {
render() {
return (
<Provider store={store}>
<React.Fragment>
<App />
</React.Fragment>
</Provider>
);
}
}
const rootElement = document.getElementById('root');
ReactDOM.render(<Main />, rootElement);
action is a description of what to change in statetype property string to describe actionaction can also have a payload passed with the type to give required context/infostate is read-only except for these actionspure functionsprevious state and new info and then returns a new state object -> the reducerinitial state when the app startsconst { createStore } = Redux; to set upstore has 3 key methods
store.getState() to get current statestore.dispatch() sends an action (with the type)store.subscribe() registers a callback to be usedstore.subscribe(method) and then run method to instantiate statelisteners are registered and watch for state changes to render
listeners.filter() that returns everything BUT the one you want removed.