unirakun / k-ramel Goto Github PK
View Code? Open in Web Editor NEWState manager for your components apps, the safe and easy way
License: MIT License
State manager for your components apps, the safe and easy way
License: MIT License
const set = reaction((action, store) => {
throw new Error('redux must be used on a good escient !')
})
It could be useful to allow users to define their own custom actions along with the ones already generated by k-redux-factory.
The actions could be then decorated with dispatch function, allowing the user to easily call it from the store
const store = createStore({
data: simpleObject({
actions: {
load: () => ({ type: 'REQUEST_DATA' }),
loaded: (data) => ({ type: 'DATA_LOADED', payload: { data } }),
},
}),
})
store.data.loaded()
store.data.load({ hello: 'world' })
Since we want to push the use of the redux-saga like API, we want to be able to dispatch very simple action like simple events. For this, our library can also help the user by generating actions for him. You just give a type name for your action and it generate the action creator for you. The action creators can take an optional payload that will be aded to the action.
const store = createStore({
data: simpleObject({
actions: {
load: 'REQUEST_DATA',
loaded: 'REQUEST_DATA',
// Also allows to give a custom action creator implementation
custom: () => ({ type: 'CUSTOM_ACTION' })
},
}),
},{
listeners: [
when(store.data.load.type, (action, store) => store.data.loaded({ hello: 'world' }))
// Dispatch { type: 'DATA_LOADED', payload: { hello: 'world' } }
]
})
I'm not entirely sure of the API. In particular, I'm not convinced by the store.data.load.type
to get the type name of the action. Perhaps by adding a toString
implementation to the function ? Allowing to just do when(store.data.loaded, (...) => ...)
?
add filters to take helpers
take( ...matches )( ...filters )( reaction )
Test to execute action : (matches1 OR matches2) AND (filter1 AND filter2)
OR
take( ...filters )( ...matches )( reaction )
const takeNoFilter = take()( ...matches )( reaction )
takeNoFilter( ...matches )( reaction )
This doesn't work (reducer in first level):
const store = createStore({
config: { type: 'simpleObject' },
})
store.config.set('config me')
expect({
state: store.getState(),
config: store.config.get(),
}).toMatchSnapshot()
So it is easier to debug.
{
type: 'NEW_ACTION_FROM_REACTON',
payload: 'reaction payload',
parent: {
type: '@@krml/INIT'
}
}
// 1. Attach { getState, dispatch } to each krf reducers
// 2. krf reducers "toContext" use that instead of given store
// 3. Have a function to set new { getState, dispatch } to each krf reducers
// 4. Use this to set store the first time
// 5. Have a function to clone the reducer tree (each krf) given a the store (clone the store)
// /!\ Take care, it should not clone the store (redux one)
// 6. In listener middleware
// a. Clone the store (with all krf reducer cloned)
// b. Set the new { getState, dispatch } with enhanced dispatch
// c. Pass the new "store" to reactions
/* const keys = [...Object.keys(reduxStore), 'listeners']
const reducerTreeKeys = Object.keys(store).filter(key => !keys.includes(key))
console.log(Object.keys(store.config)) */
this issue is about takeWith
where currying is reversed from take
take(filter)(reaction)
takeWith(reaction)(filter)
The approach is more convenient to write OR:
take version
take(filter1, andFilter2)(reactionImpl)
take(orFilter3)(reactionImpl)
takeWith version
const reaction = takeWith(reactionImpl)
// ...
takeWith(filter1, andFilter2)
takeWith(orFilter3)
takeWith
is not in the lib ?Good question! This is because this example shows that we are not familiar with this pattern, since we can't find a propre name to complete
fonction:
// todos.js
import { takeWith } from 'k-simple-state'
export const complete = takeWith(action, store) => {
const { todos } = store.data
const todo = todos.get(action.payload)
todos.set({ ...todos, completed: true })
}
// listeners.js
import { complete } from './todos'
export default [
// here it seems odd to me to call a fonction 'complete' passing an action type :)
complete('@@ui/CLICKED_COMPLETE'),
]
When someone will find a proper naming convention we will write the takeWith
and publish it in this lib.
As long as we can't find that we don't publish it 🙂
Use this: https://github.com/developit/stockroom
Or reimplement the idea ?
Dispatch an INIT action when the provider has loaded the store to simplify implementations like that :
export default compose(
provider(store),
inject(st => ({ load: () => { st.dispatch({ type: '@@ui/APP_LOADED' }) } })),
loader(),
)(App)
provider
could dispatch an actions names :
@@kst/STORE_PROVIDED
,@@kst/STORE_LOADED
,@@kst/INIT
cut the big createState.js
file into severals
And this is sad :(
Ispired by the Harry Potter spell reducto
(reference here)
Rules:
redux
in it, so we can change implementation in a near future if we'd like tok-
in prefix but this is not mandatoryname
Thank for your help everyone.
@delphinemillet @guillaumecrespel @bpetetot @frinyvonnick @EmrysMyrddin
I think we could removed function store.createStore()
in the API
🚨 You need to enable Continuous Integration on all branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial
branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.
Because the written code is shorter with this lib than with REduX, and it's more powerful than the T-REX ! And even if you don't use redux in the future, it's still more powerful than the T-REX !
And its a short name :)
@bpetetot you already did this right ? 😅
Maybe we should refactor the driver so drivers returns this interface everytime:
And we use them like that:
export default createStore(
description,
{
drivers: [
http(),
form(state => state.form),
reduxLittleRouter(routes, state => state.router, routerImpl),
]
}
)
And k-ramel
use the returned interface to configurate the store where it needs to be, enhancer would be pushed the same order as driver declaration.
seeing the example here
https://github.com/alakarteio/k-simple-state#create-a-simple-store
wouldn't be a good idea to ditch the imperative api to on dispatching lense to the reducers ?
and using the same lense to select the data from the store so it can be used in map state to props etc. ?
Many other toughts store enhancer seems to be a better fit than wrapping a redux store, maybe all this can be achieved using a higher order reducer to and avoid creating a knowledge gap between mainstream redux api and tools (like connect).
k-ramel already propose the ability to load listeners dynamically.
Do you think that it could also load some reducers dynamically in order to have a complete separation of some screens ?
For example, in my app, I have an admin page that managing all my application users. And I have specific reducers (users data, admin screens data) specific to that page. So I could have a container loading k-ramel reducers and listeners specific to it :
import { updateStore, when } from '@k-ramel/react'
import AdminPage from './AdminPage'
updateStore({
data: { users: { type: 'keyValue', id: 'uid' } },
ui: { admin: { type: 'simpleObject' } },
}, [
when('MY_ADMIN_ACTION')(() => { /* do something */ })
]})(AdminPage)
And it could be a great optimisation for apps using code splitting (dynamic imports).
An error is thrown if the function given to inject
return somehting else than an object.
The simplest example to reproduce :
inject(() => {})(Component)
Should this trhow an error ? A warning ? Nothing ?
@@kst
actions prefix--
@delphinemillet @guillaumecrespel @bpetetot @frinyvonnick @EmrysMyrddin @AFaugeras @Taranys @Okazari
Hi !
I just changed the name on github.
But I am not fan of this once again.
@delphinemillet said it could be cool to have food
name since the organisation is alakarte(io)
. An I think it's great.
What your tough about it ?
Should we find a name related to food or keep k-rex ?
Vote k-rex: ❤️
Or vote for food name: 👍
-> If you have food name idea feel free to respond to this thread.
🚨 You need to enable Continuous Integration on all branches of this repository. 🚨
To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.
Since we didn’t receive a CI status on the greenkeeper/initial
branch, it’s possible that you don’t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.
If you have already set up a CI for this repository, you might need to check how it’s configured. Make sure it is set to run on all new branches. If you don’t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/
.
Once you have installed and configured CI on this repository correctly, you’ll need to re-trigger Greenkeeper’s initial pull request. To do this, please delete the greenkeeper/initial
branch in this repository, and then remove and re-add this repository to the Greenkeeper App’s white list on Github. You'll find this list on your repo or organization’s settings page, under Installed GitHub Apps.
prefix = path
The API, since #20, is not as simple as I wanted it to be.
Find a way to make it easier to use ?
In different use cases, sometimes, I need to reset the store or a part of the store.
For example, when I switch from a connected user to another I need to reset a huge part of the store and its quite exhaustive to do. Because I have to call each reset()
methods of my reducers, or create RESET
actions to my custom reducers. And, in the future, if I have to add a new reducer, I dont must forget to reset it when needed.
I was thinking about a method :
store.reset()
: apply the initial state to the entire storestore.reset('path')
: apply the initial state from the given pathhint: react-redux
bpetetot/conference-hall#123 (comment)
k-ramel
@k-ramel/react
@k-ramel/driver-http
@k-ramel/...
But keep the mono-repo
Waiting for #69 so the lib are not requiring redux-form
everytime... for everycases.
driver
import { setSubmitSucceeded, getFormValues, setSubmitFailed, startSubmit, stopSubmit, isSubmitting } from 'redux-form'
const asyncSubmit = (name, dispatch, getState) => async (callback, ...options) => {
dispatch(startSubmit(name))
await callback(...options)
if (isSubmitting(name)(getState())) dispatch(stopSubmit)
}
export default ({ dispatch, getState }) => name => ({
getFormValues: () => getFormValues(name, state => state.ui.form)(getState()),
setSubmitFailed: (...fields) => dispatch(setSubmitFailed(name, ...fields)),
setSubmitSucceeded: () => dispatch(setSubmitSucceeded(name)),
startSubmit: () => dispatch(startSubmit(name)),
stopSubmit: errors => dispatch(stopSubmit(name, errors)),
asyncSubmit: (callback, ...options) => asyncSubmit(name, dispatch, getState)(callback, ...options),
})
Example usage in a reaction (plugued to a listener)
export const login = reaction((action, store, { http, form }) => {
// retrieve credentials from redux
const signin = form('signin')
const values = signin.getFormValues()
// submit
signin.asyncSubmit(http('AUTH').post, '/api/login')
})
Something with this API:
import { createStore, take } from 'k-simple-state'
const store = createStore({
config: { type: 'simpleObject' },
save: { type: 'simpleObject' },
}, {
listen: [
take(/SET_CONFIG$/g, (action, store) => {
console.log({ action })
store.save.set('saved')
}
],
})
import { createStore, keyValue, simpleObject } from 'k-simple-state'
const store = createStore({
data: {
todos: { type: 'keyValue', key: 'id' } // or keyValue({ key: 'id' })
},
ui: {
screens: {
login,
},
},
}, {
middlewares: [reduxThunk, logger, devtools],
})
This name is about this spicy mix: https://fr.wikipedia.org/wiki/Zaatar.
I choose a spicy mix because we mix redux with some mobx-state-tree concepts.
And maybe some Cycle concepts in the end.
This is about this in redux:
const store = createStore(
reducers,
initState,
compose(
enhancer,
applyMiddleware(sagaMiddleware, middleware),
/* eslint-env browser */
window.devToolsExtension ? window.devToolsExtension() : f => f,
),
)
shouldComponentUpdate
in inject()
must ignore functions.
import { inject } from "k-simple-state/react";
import App from "./app";
const mapProps = ({ getState, dispatch }) => ({
count: getState().count,
increment: () => dispatch({ type: "INCREMENT" }),
decrement: () => dispatch({ type: "DECREMENT" })
});
export default inject(mapProps)(App);
Today shouldComponentUpdate
will aways be true
due to functions increment
and decrement
.
take(['ACTION1', 'ACTION2'] console.log)
Allow this:
store.dispatch('@@ui/TODO_CLICKED')
This still works:
store.dispatch({ type: '@@ui/TODO_CLICKED' })
Add hasKey
selector from k-redux-factory.
Wait for #30 to do this
I don't like that name because simple is not easy and easy is not simple
I have opened a question, because I don't know if it's the philosophy of the library, but I think it could be useful in some cases.
Simple example :
import { inject } from '@k-ramel/react'
import MyComponent from './myComponent'
inject((store, props, { router }) => ({
id: router.getParam('id'),
onClick: () => router.push('/mypath')
}))(MyComponent)
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.