Skip to content

Instantly share code, notes, and snippets.

@redknitin
Created August 21, 2018 14:11
Show Gist options
  • Save redknitin/958c265f09c3d1083c658544f511517c to your computer and use it in GitHub Desktop.
Save redknitin/958c265f09c3d1083c658544f511517c to your computer and use it in GitHub Desktop.
Using a Redux Store
import React, { Component } from 'react';
import './App.css';
import { createStore } from 'redux';
const CHANGE_CARD_VISIBILITY = 'CHANGE_CARD_VISIBILITY';
function rootReducer(state = [], action) {
switch(action.type) {
case CHANGE_CARD_VISIBILITY:
return Object.assign({}, state, { isCardVisible: action.isVisible });
default:
return state;
}
}
let store = createStore(rootReducer, {
isCardVisible: 'no'
});
class App extends Component {
constructor() {
super();
store.subscribe(() => {
console.log(store.getState());
this.refs.theGreatToggler.innerHTML = store.getState().isCardVisible;
});
this.toggleVisibility = this.toggleVisibility.bind(this);
}
toggleVisibility() {
if (store.getState().isCardVisible == 'yes') {
store.dispatch({type: CHANGE_CARD_VISIBILITY, isVisible: 'no'});
} else
if (store.getState().isCardVisible == 'no') {
store.dispatch({type: CHANGE_CARD_VISIBILITY, isVisible: 'yes'});
}
}
render() {
return (
<div className="App">
<button onClick={this.toggleVisibility}>Toggle</button>
<br />
<span ref="theGreatToggler">{store.getState().isCardVisible}</span>
</div>
);
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment