Skip to content

Instantly share code, notes, and snippets.

@tfiechowski
tfiechowski / rootReducer.js
Last active April 2, 2018 09:52
WIP: Redux root reducer caching state in local storage
import { CHANGE_TEAM } from 'modules/Team/Team';
const getCurrentTeamId = () => window.localStorage.getItem('current-team');
const readTeamData = teamId => {
const newStateData = window.localStorage.getItem(`team-data-${teamId}`);
if (newStateData) {
return JSON.parse(newStateData);
}
@tfiechowski
tfiechowski / cache-child-state.js
Created April 6, 2018 09:18
Cache child component state
class Child extends Component {
state = this.props.cachedState
? this.props.cachedState
: {
value: 0,
};
componentWillUnmount() {
if (this.props.saveState) {
this.props.saveState(this.state);
import api from './api';
export const ADD_PHOTOS = 'Photos/ADD_PHOTOS';
export function addPhotos(photos) {
return {
type: ADD_PHOTOS,
payload: photos,
};
}
import { ADD_PHOTOS } from './actions';
function getInitialState() {
return {
photos: [],
};
}
export default function reducer(state = getInitialState(), action) {
switch (action.type) {
import { connect } from 'react-redux';
import PhotoList from 'components/PhotoList';
import { fetchPhotos } from './modules/Photos/actions';
const mapStateToProps = state => ({
photos: state.photos.photos,
});
const mapDispatchToProps = {
import { Component, createContext } from 'react';
import PropTypes from 'prop-types';
import api from './api';
const { Consumer, Provider } = createContext({
photos: [],
});
export { Consumer };
import { PhotosConsumer } from './contexts';
import PhotoList from 'components/PhotoList';
export default function ContextPhotoListContainer() {
return (
<PhotosConsumer>
{({ photos, fetchPhotos }) => <PhotoList photos={photos} fetchPhotos={fetchPhotos} />}
</PhotosConsumer>
);
}
import { combineReducers, createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import photos from './modules/Photos/reducer';
const rootReducer = combineReducers({ photos });
export default createStore(rootReducer, applyMiddleware(thunk));
import 'regenerator-runtime/runtime';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import Container from 'components/Container';
import ReduxPhotoListContainer from './ReduxPhotoListContainer';
import store from './store';
render(
import 'regenerator-runtime/runtime';
import { PhotosProvider } from './contexts';
import Container from 'components/Container';
import ContextPhotoListContainer from './ContextPhotoListContainer';
import { render } from 'react-dom';
render(
<PhotosProvider>