Skip to content

Instantly share code, notes, and snippets.

@jdltechworks
Last active September 26, 2017 00:25
Show Gist options
  • Save jdltechworks/a1c3363815b76549a64cdcaa4a74f8db to your computer and use it in GitHub Desktop.
Save jdltechworks/a1c3363815b76549a64cdcaa4a74f8db to your computer and use it in GitHub Desktop.
My react-redux setup
import React, { cloneElement, Component, Children } from 'react'
import { connect } from 'react-redux'
import omit from 'lodash/omit'
class App extends Component {
render() {
const { props } = this
const noform = omit(props, 'form')
return(
<div className="main">
{Children.map(this.props.children, (child) => {
return cloneElement(child, { ...noform })
})}
</div>
)
}
}
export default connect(state => state)(App)
import React, { Component } from 'react'
import { Router, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import composeStore from './store-composer'
import routes from './routes'
const { store, actions, history } = composeStore(
browserHistory,
window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
)
class ClientProvider extends Component {
/**
* Works like an hoc adds
* current props and inherited props from the mounted component plus actions
* in every component that is in our routes
* @param {[type]} Component [description]
* @param {[type]} existingProps [description]
* @return {Component} exsting component with passed props
*/
withActions(ExistingComponent, existingProps) {
const { props } = this
const allProps = {
...props,
...existingProps,
actions
}
return <ExistingComponent {...allProps} />
}
render() {
const { withActions } = this
return(
<Provider store={store}>
<Router history={history}
createElement={withActions.bind(this)}
routes={routes} />
</Provider>
)
}
}
export default ClientProvider
import { render } from 'react-dom'
import ClientProvider from './ClientProvider'
//For laravel
window.getInitialState = (props, target) => {
const mount = document.getElementById(target)
render(<ClientProvider {...props} />, mount)
}
import {createConstants, createReducer} from 'redux-module-builder'
import {createApiHandler, createApiAction} from 'redux-module-builder/api'
import map from 'lodash/map'
export const types = createConstants('auth')(
'LOGIN',
'CHECK',
'LOGOUT',
'REGISTER',
'REGISTER_SUCCESS',
'ERROR',
'IS_NOT_AUTHENITCATED',
'IS_AUTHENITCATED',
'IS_REGISTERING'
)
export const initialState = {
isLoggingIn: false,
isLoggedIn:false,
loggedOut: true,
session: {}
}
//Pangit e refactor haha
export const actions = {
signup(props) {
return (dispatch, getState) => {
const body = new FormData()
dispatch({ type: types.IS_REGISTERING })
map(props, (value, key) => {
body.append(key, value)
})
return fetch('/register', {
method: 'POST',
credentials: 'same-origin',
body
})
.then((res) => res.json())
.then((session) => {
dispatch({ type: types.REGISTER_SUCCESS, session })
}).catch(err => dispatch({ type: types.ERROR, err}))
}
},
login(email, password) {
const body = new FormData()
body.append('email', email)
body.append('password', password)
/**
* return an actions type and return objects of that type
* you can use the fetch api here in there return section
*
* @param {[type]} dispatch [description]
* @return {[type]} [description]
*/
return (dispatch, getState) => {
//send a fetch api here
dispatch({ type: types.LOGIN })
return fetch('/login', {
method: 'POST',
credentials: "same-origin",
body
}).then((res) => {
return res.json()
}).then((session) => {
dispatch({ type: types.IS_AUTHENITCATED, session })
dispatch(push('/'))
}).catch(error => dispatch({ type: types.ERROR, error }))
}
},
logout() {
return (dispatch, getState) => {
//send a fetch api here
const body = new FormData()
body.append('_token', '')
return fetch('/logout', {
method: 'POST',
credentials: "same-origin",
body
}).then((res) => {
return res.json()
}).then((session) => {
dispatch({ type: types.LOGOUT, session: {} })
}).catch(error => dispatch({ type: types.ERROR, error }))
}
}
}
export const reducer = createReducer({
[types.LOGOUT]: (state, { session }) => {
return {
...state,
loggedOut: true,
session: '',
loggedIn: false
}
},
[types.REGISTER]: (state, { session }) => {
return {
...state,
session
}
},
[types.IS_AUTHENITCATED]: (state, { session }) => {
return {
...state,
loggedIn: true,
loggedOut: false,
session
}
},
[types.ERROR]: (state, { error }) => {
console.log(error)
return {
...state,
...error
}
}
})
import { combineReducers } from 'redux'
import { createRootReducer as processModules } from 'redux-module-builder'
import { routerReducer as routing, push } from 'react-router-redux'
import { reducer as form } from 'redux-form'
/**
* import your modules here
* sample
* import MyModule from './MyModule'
*/
import * as Auth from './modules-sample'
/**
* You can register your module here
* @type {Object}
*/
const modules = {
Auth
}
const initialActions = {
routing: {
navigateTo: path => dispatch => dispatch(push(path))
}
}
/**
* You can add reducers from external npm modules
* @type {Object}
*/
const initialReducers = {
form,
routing
}
const initialState = {}
/**
* We are actually processing the modules why call createRootReducer if the function generates actions
* @type {object}
*/
const bundled = processModules(modules, {
initialInitialState: initialState,
initialActions,
initialReducers
})
const reducers = combineReducers(bundled.reducers)
/**
* Function to activate the generated bundle
* @return {object} reducers, actions, initialState
*/
export default () => {
return {
reducers,
actions: bundled.actions,
initialState: bundled.initialState
}
}
import { Route, IndexRoute } from 'react-router'
import React, { Component } from 'react'
import App from './App'
//You can create container of your own
class Home extends Components {
render() {
return(
<div className="home">Home component</div>
)
}
}
const routes = (
<Route path="/" component={App}>
<IndexRoute component={Home} />
</Route>
)
export default routes
import modules from './modules'
import thunkMiddleware from 'redux-thunk'
import { createStore, compose, applyMiddleware } from 'redux'
import { bindActionCreatorsToStore } from 'redux-module-builder'
import { routerMiddleware, syncHistoryWithStore } from 'react-router-redux'
const { reducers, actions, initialState } = modules()
let middlewares = [
thunkMiddleware
]
const setComposer = (composer) => {
if(composer) return composer
return compose
}
const setHistoryType = (historyType, request) => {
if(request) return historyType(request.url)
return historyType
}
export default (historyType, composer, request) => {
const create = setComposer(composer)
const history = setHistoryType(historyType, request)
let composeStore = create(
applyMiddleware(...middlewares),
)(createStore)
const store = composeStore(reducers, initialState)
middlewares.push(
routerMiddleware(historyType)
)
return {
history: syncHistoryWithStore(history, store),
store,
actions: bindActionCreatorsToStore(actions, store)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment