Created
January 9, 2016 11:56
-
-
Save bodhi/31abb4655085ffec87a5 to your computer and use it in GitHub Desktop.
Toy auth wrapper component for React+Redux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require('normalize.css'); | |
require('styles/App.css'); | |
import React from 'react'; | |
import { connect, Provider } from 'react-redux'; | |
import { createStore } from 'redux'; | |
const store = createStore((s, a) => { | |
switch (a.type) { | |
case "LOG_IN": | |
return Object.assign({}, s, { loggedIn: true }); | |
case "LOG_OUT": | |
return Object.assign({}, s, { counter: 0, loggedIn: false }); | |
case "INCREMENT": | |
return Object.assign({}, s, { counter: s.counter + 1 }); | |
} | |
return s; | |
}, { loggedIn: false, counter: 0 }); | |
const logIn = () => ({ type: "LOG_IN", loggedIn: true }); | |
const logOut = () => ({ type: "LOG_OUT", loggedIn: false }); | |
const increment = () => ({ type: "INCREMENT" }); | |
let Toggle = ({loggedIn, logIn, logOut}) => ( | |
<div> | |
<h1>status: {loggedIn ? "logged in" : "logged out"}</h1> | |
<button onClick={logIn}>Log In</button> | |
<button onClick={logOut}>Log Out</button> | |
</div> | |
); | |
const konnect = connect(({ loggedIn }) => ({ loggedIn }), { logIn, logOut }); | |
Toggle = konnect(Toggle); | |
let Authed = ({loggedIn, children}) => { | |
if (loggedIn) { | |
return <div>{children}</div> | |
} else { | |
return <div>UNAUTHORIZED!</div> | |
} | |
}; | |
Authed = konnect(Authed); | |
let Unauthed = ({loggedIn, children}) => { | |
if (!loggedIn) { | |
return <div>{children}</div> | |
} else { | |
return <div>Log out to see this</div> | |
} | |
}; | |
Unauthed = konnect(Unauthed); | |
let Counter = ({ counter, increment }) => ( | |
<div> | |
<h1>Counter: {counter}</h1> | |
<button onClick={increment}>+</button> | |
</div> | |
) | |
Counter = connect(({ counter }) => ({counter}), {increment})(Counter); | |
const AppComponent = () => ( | |
<Provider store={store}> | |
<div className="index"> | |
<Toggle /> | |
<Authed> | |
<Counter /> | |
</Authed> | |
<Unauthed> | |
Welcome to app! | |
</Unauthed> | |
</div> | |
</Provider> | |
); | |
export default AppComponent; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment