Last active
April 30, 2017 16:45
-
-
Save kocisov/8e1eb71c969cc68db460b1b926096d6d to your computer and use it in GitHub Desktop.
redux215
This file contains hidden or 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
// Component.js | |
import React from 'react' | |
// get props from redux store | |
export default ({ user, login }) => | |
<div> | |
{!user.isAuthenticated ? | |
<div> | |
<button onClick={login}> | |
Login with StreamLabs | |
</button> | |
</div> : | |
<div> | |
You are authenticated {user.name} | |
</div> | |
} | |
</div> | |
// Container.js | |
import { connect } from 'react-redux' | |
// function to login | |
import { login } from './Reducer' // bottom of file | |
// logic-less component ^at top of this file | |
import UI from './component' | |
// connect | |
// first arg is function that returns props to UI component | |
// second arg is function that returns functions as props to UI component | |
// then you pass UI Component | |
export default connect(({ user }) => ({ user }), { | |
login | |
})(UI) | |
// Reducer.js (duck) | |
const USER_LOGGED_IN = '_/user/USER_LOGGED_IN' | |
const USER_CALLED_LOGIN = '_/user/USER_CALLED_LOGIN' | |
const USER_CALLED_LOGIN = '_/user/USER_CALLED_LOGGED' | |
export default function user (state = {}, action) { | |
switch (action.type) { | |
case USER_CALLED_LOGIN: | |
return { | |
...state, | |
showNotification: true | |
} | |
// so bad name xd | |
case USER_CALLED_LOGGED: | |
return { | |
...state, | |
showNotification: false | |
} | |
case USER_LOGGED_IN: | |
return { | |
...state, | |
/* | |
we spread everything in action.payload: | |
{ | |
name: '__', | |
id: 1, | |
points: 123 | |
} | |
instead of doing it manually | |
{ | |
name: action.payload.name, | |
id: action.payload.id, | |
points: action.payload.points, | |
} | |
*/ | |
...action.payload | |
} | |
default: | |
return state | |
} | |
} | |
// async function | |
// using redux-thunk middleware | |
export const login = () => dispatch => { | |
// something like logging in notification | |
dispatch(USER_CALLED_LOGIN) | |
// fake server delay | |
setTimeout(() => { | |
// user logged in | |
dispatch(USER_LOGGED_IN, { | |
name: '__', | |
id: 1, | |
points: 123 | |
}) | |
}, 2500) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment