Giter VIP home page Giter VIP logo

redux-zero's Introduction

redux zero logo

A lightweight state container based on Redux

Read the intro blog post


codacy build npm downloads license dependencies

Table of Contents

Installation

To install the stable version:

npm i redux-zero

This assumes that you’re using npm with a module bundler like webpack

How

ES2015+:

import createStore from "redux-zero";
import { Provider, connect } from "redux-zero/react";

TypeScript:

import * as createStore from "redux-zero";
import { Provider, connect } from "redux-zero/react";

CommonJS:

const createStore = require("redux-zero");
const { Provider, connect } = require("redux-zero/react");

UMD:

<!-- the store -->
<script src="https://unpkg.com/redux-zero/dist/redux-zero.min.js"></script>

<!-- for react -->
<script src="https://unpkg.com/redux-zero/react/index.min.js"></script>

<!-- for preact -->
<script src="https://unpkg.com/redux-zero/preact/index.min.js"></script>

<!-- for vue -->
<script src="https://unpkg.com/redux-zero/vue/index.min.js"></script>

<!-- for svelte -->
<script src="https://unpkg.com/redux-zero/svelte/index.min.js"></script>

Example

Let's make an increment/decrement simple application with React:

First, create your store. This is where your application state will live:

/* store.js */
import createStore from "redux-zero";

const initialState = { count: 1 };
const store = createStore(initialState);

export default store;

Then, create your actions. This is where you change the state from your store:

/* actions.js */
const actions = store => ({
  increment: state => ({ count: state.count + 1 }),
  decrement: state => ({ count: state.count - 1 })
});

export default actions;

By the way, because the actions are bound to the store, they are just pure functions :)

Now create your component. With Redux Zero your component can focus 100% on the UI and just call the actions that will automatically update the state:

/* Counter.js */
import React from "react";
import { connect } from "redux-zero/react";

import actions from "./actions";

const mapToProps = ({ count }) => ({ count });

export default connect(
  mapToProps,
  actions
)(({ count, increment, decrement }) => (
  <div>
    <h1>{count}</h1>
    <div>
      <button onClick={decrement}>decrement</button>
      <button onClick={increment}>increment</button>
    </div>
  </div>
));

Last but not least, plug the whole thing in your index file:

/* index.js */
import React from "react";
import { render } from "react-dom";
import { Provider } from "redux-zero/react";

import store from "./store";

import Counter from "./Counter";

const App = () => (
  <Provider store={store}>
    <Counter />
  </Provider>
);

render(<App />, document.getElementById("root"));

Here's the full version: https://codesandbox.io/s/n5orzr5mxj

By the way, you can also reset the state of the store anytime by simply doing this:

import store from "./store";

store.reset();

More examples

Actions

There are three gotchas with Redux Zero's actions:

  • Passing arguments
  • Combining actions
  • Binding actions outside your application scope

Passing arguments

Here's how you can pass arguments to actions:

const Component = ({ count, incrementOf }) => (
  <h1 onClick={() => incrementOf(10)}>{count}</h1>
);

const mapToProps = ({ count }) => ({ count });

const actions = store => ({
  incrementOf: (state, value) => ({ count: state.count + value })
});

const ConnectedComponent = connect(
  mapToProps,
  actions
)(Component);

const App = () => (
  <Provider store={store}>
    <ConnectedComponent />
  </Provider>
);

Access props in actions

The initial component props are passed to the actions creator.

const Component = ({ count, increment }) => (
  <h1 onClick={() => increment()}>{count}</h1>
);

const mapToProps = ({ count }) => ({ count });

const actions = (store, ownProps) => ({
  increment: state => ({ count: state.count + ownProps.value })
});

const ConnectedComponent = connect(
  mapToProps,
  actions
)(Component);

const App = () => (
  <Provider store={store}>
    <ConnectedComponent value={10} />
  </Provider>
);

Combining actions

There's an utility function to combine actions on Redux Zero:

import { connect } from "redux-zero/react";
import { combineActions } from "redux-zero/utils";

import Component from "./Component";
import firstActions from "../../actions/firstActions";
import secondActions from "../../actions/secondActions";

export default connect(
  ({ params, moreParams }) => ({ params, moreParams }),
  combineActions(firstActions, secondActions)
)(Component);

Binding actions outside your application scope

If you need to bind the actions to an external listener outside the application scope, here's a simple way to do it:

On this example we listen to push notifications that sends data to our React Native app.

import firebase from "react-native-firebase";
import { bindActions } from "redux-zero/utils";
import store from "../store";
import actions from "../actions";

const messaging = firebase.messaging();
const boundActions = bindActions(actions, store);

messaging.onMessage(payload => {
  boundActions.saveMessage(payload);
});

Async

Async actions in Redux Zero are almost as simple as sync ones. Here's an example:

const mapActions = ({ setState }) => ({
  getTodos() {
    setState({ loading: true });

    return client
      .get("/todos")
      .then(payload => ({ payload, loading: false }))
      .catch(error => ({ error, loading: false }));
  }
});

They're still pure functions. You'll need to invoke setState if you have a loading status. But at the end, it's the same, just return whatever the updated state that you want.

And here's how easy it is to test this:

describe("todo actions", () => {
  let actions, store, listener, unsubscribe;
  beforeEach(() => {
    store = createStore();
    actions = getActions(store);
    listener = jest.fn();
    unsubscribe = store.subscribe(listener);
  });

  it("should fetch todos", () => {
    nock("http://someapi.com/")
      .get("/todos")
      .reply(200, { id: 1, title: "test stuff" });

    return actions.getTodos().then(() => {
      const [LOADING_STATE, SUCCESS_STATE] = listener.mock.calls.map(
        ([call]) => call
      );

      expect(LOADING_STATE.loading).toBe(true);
      expect(SUCCESS_STATE.payload).toEqual({ id: 1, title: "test stuff" });
      expect(SUCCESS_STATE.loading).toBe(false);
    });
  });
});

Middleware

The method signature for the middleware was inspired by redux. The main difference is that action is just a function:

/* store.js */
import createStore from "redux-zero";
import { applyMiddleware } from "redux-zero/middleware";

const logger = store => (next, args) => action => {
  console.log("current state", store.getState());
  console.log("action", action.name, ...args);
  return next(action);
};

const initialState = { count: 1 };
const middlewares = applyMiddleware(logger, anotherMiddleware);

const store = createStore(initialState, middlewares);

export default store;

DevTools

You can setup DevTools middleware in store.js to connect with Redux DevTools and inspect states in the store.

/* store.js */
import createStore from "redux-zero";
import { applyMiddleware } from "redux-zero/middleware";
import { connect } from "redux-zero/devtools";

const initialState = { count: 1 };
const middlewares = connect ? applyMiddleware(connect(initialState)) : [];
const store = createStore(initialState, middlewares);

export default store;

Also, these are unofficial tools, maintained by the community:

TypeScript

You can use the BoundActions type to write your React component props in a type safe way. Example:

import { BoundActions } from "redux-zero/types/Actions";

interface State {
  loading: boolean;
}

const actions = (store, ownProps) => ({
  setLoading: (state, loading: boolean) => ({ loading })
});

interface ComponentProps {
  value: string;
}

interface StoreProps {
  loading: boolean;
}

type Props = ComponentProps & StoreProps & BoundActions<State, typeof actions>

const Component = (props: Props) => (
  <h1 onClick={() => props.setLoading(!props.loading)}>{props.value}</h1>
);

const mapToProps = (state: State): StoreProps => ({ loading: state.loading });

const ConnectedComponent = connect<State, ComponentProps>(
  mapToProps,
  actions
)(Component);

const App = () => (
  <Provider store={store}>
    <ConnectedComponent value={10} />
  </Provider>
);

By doing this, TypeScript will know the available actions and their types available on the component's props. For example, you will get a compiler error if you call props.setLoding (that action doesn't exist), or if you call it with incorrect argument types, like props.setLoading(123).

Inspiration

Redux Zero was based on this gist by @developit

Roadmap

  • Make sure all bindings are working for latest versions of React, Vue, Preact and Svelte
  • Add time travel

Help is needed for both of these

Docs

redux-zero's People

Contributors

343dev avatar arminhaghi avatar chevsky avatar d3x7r0 avatar dependabot[bot] avatar dmmulroy avatar emilianox avatar englercj avatar esperancajs avatar eyamenko avatar fdaciuk avatar gebeto avatar gnbaron avatar guilherme6191 avatar guru107 avatar jetako avatar k1r0s avatar kiho avatar leobetosouza avatar leonardovillela avatar malbernaz avatar markdhel avatar matheusml avatar mochiya98 avatar pabloalexandre avatar ricardo-devis-agullo avatar sidkwok avatar tkvw avatar winstonfassett avatar yeojz avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

redux-zero's Issues

Add Preact bindings

Now that createStore is decoupled from Provider and connect we can add preact bindings.

Arquitechture Question - Why Not Reducers?

Hi everyone.

First, thanks to created this project. I always searching state management concepts and Flux Arquitechture,really like this pattern and all power that Flux returns to project.

I liked that you make with actions and stores, principally the way to use into components.

So, i have a arquitectural question: Why not reducers or other structure to contain separated the operationals can modify state?

Middleware: Is it possible to get next state

Hello,

I'm new to the middleware part of redux-zero and I wan't to write a small middleware that get the state after the application of the action. Is this possible with the middleware implementation of redux-zero?

Something like this doesn't work in my application:

const logger = store => next => action => {
  console.log("state before change", store.getState());
  const result = next(action); 
  console.log("state after change", store.getState());
  return result;
};

result will be a Promise which will resolve to undefined

I also tried to resolve the promise with async/await

Am I doing something wrong?

Other than that I'm loving redux-zero :-)

Thx and greetings from Cologne

Bart

Actions run onClick but not in class handlers

I just started using Redux Zero and came across an issue, I am most certainly making a mistake!

When I use onClick={action} , state is successfully updated and everything is great :)

When I move {action} into my class handler onClick{this.handleRefresh}, state is not updated and the function is not called.

I've attached my full setup.
React V16

actions.js

import store from './store';

export const refreshingOn = () => {
	store.setState({
		refreshStatus: true
	});
};

export const refreshingOff = () => {
	store.setState({
		refreshStatus: false
	});
};

LibraryRefreshIcon.js

import React, { Component } from 'react';
import RefreshIcon from 'material-ui-icons/Refresh';
import './LibraryRefresh.css';
import { connect } from 'redux-zero/react';
import { refreshingOn, refreshingOff } from '../../containers/Root/actions';

const mapToProps = ({ refreshStatus }) => ({ refreshStatus });

class LibraryRefreshIcon extends Component {
	constructor(props) {
		super(props)
		this.state = {
			iconStyle		: 'libraryRefreshIcon',
		};
	}

	handleRefresh = () => {
		console.log(refreshingOn);
		this.setState({
			iconStyle: 'libraryRefreshIconAnimation',
		});
		{refreshingOn}

		setTimeout( () => {
			this.setState({
				iconStyle		: 'libraryRefreshIcon',
			});
			{refreshingOff}
		}, 400);
	}

	render() {
		console.log(this.props);
		console.log(refreshingOn);
			return (
			<div className='libraryRefreshIconContainer'>
				<RefreshIcon onClick={this.handleRefresh} className={this.state.iconStyle}/>
			</div>
		);
	}
}

export default connect(mapToProps)(LibraryRefreshIcon);

Thanks for anyhelp! I found Redux to be really complicated and Zero already feels much easier to learn/use. Thank you :)

Svelte connect & example.

I like to add Svelte support in redux-zero.
Please review my project and let me know what I have to do more to make PR.
https://github.com/Kiho/redux-zero
While I was making this I hit 2 problems.

  1. React dependency - Svelte does not need react at all
  2. npm run format command break on windows machine(not sure maybe only me).

async/await example?

Hi there,

First of all, redux-zero looks really great and simple.

Could you please provide an example with async/await or Promises?

Thanks!

Add an example with React

Add an example (to the examples folder) of an application with React using Redux Zero.
PS.: Counter, To-Do List, etc

TypeScript module resolution

According to this microsoft/TypeScript#2568 (comment)
looks like you need to change this entry in package.json from
"typings": "dist/index.d.ts" to "types": "dist/index.d.ts"
I try to reference redux-zero/svelte in ts module but it does not work.
I had to change import statement import { getActions } from 'redux-zero/dist/svelte' to make it work.

Add chrome dev tools

As discussed here #19 , now that we have a middleware, we can implement some sort of dev tools.

Is there a way to compatible with redux middleware?

Anyway. redux got a lot of middleware in community, many of them is powerful and useful.

If it is compatible, It must be pretty cool.

It mean people don't need to rewrite their middleware and redux-zero can use it well.

This will surely attract a lot of people to use.

Pros and cons of redux-zero vs fast-redux

Nice idea! Please also take a look onto my attempt to make Redux simpler: https://github.com/dogada/fast-redux

I made fast-redux to reduce classic Redux boilerplate, achieve O(1) store update speed and allow extending a store with new actions when you dynamically load new javacript code using code splitting. My version is backward compatible with Redux and Redux DevTools however.

Can you, please, clarify some issues about your approach?

  1. How to use async actions (redux-thunk, redux-promise, etc)?
  2. Is it possible to add new actions to the existing store (please see https://github.com/dogada/fast-redux/tree/master/examples/nextjs-preact-code-splitting for a demo of this scenario)?
  3. How do you separate in store data created by different components? How to serialize store on server and restore on client? Do you have example of using redux-zero with Server Side Rendering?
  4. Can I use redux-zero with reselect?

Bind actions instead of coupling them to the store

Hiya!

Right now, actions must import an instance of the store in order to invoke setState(). This creates a tight coupling of actions to the store, making testing require mocking that import. It's a short-circuit that starts out quite nice (just import the store instance), but can get a bit hairy later on (can only have one store, can't compose actions, etc).

Here's a testing use-case that shows what I mean:

import { increment, decrement } from './actions'
import store from './store'  // not part of the unit being tested

increment()
expect(store.getState()).to.eql({ count: 1 })   // asserting on another module
// ^ what if something else had changed the store? or messed with store.setState?

I'd like to propose a few lightweight options for making actions "late-bound". Some of this comes from other experiments I've done with the Gist I sent.

Note: in the examples I'm using Object in place of mapStateToProps - I'm just using it as the identity function so that the entire store state is passed as props for the examples.

1. Simple store binding function

This is fairly analogous to redux's approach, just replacing dispatch() with the store instance itself. connect() accepts a function as a 2nd argument that expects (store) and returns actions that mutate that store. Perks: this remains compatible and nearly identical to the readme examples, the only difference being that store is injected rather than imported (therein removing the singleton issue).

import { createStore, Provider, connect } from 'redux-zero'
export default () => <Provider store={createStore()}><App /></Provider>

const mapStateToProps = Object  // or whatever

// same as actions.js from the readme, just instantiable with any `store`:
const createActions = store => ({
  increment() {
    // arguments passed to props.increment() are forwarded here
    store.setState({
      count: store.getState().count + 1
    })
  }
})

const App = connect(mapStateToProps, createActions)(
  ({ count, increment }) => (
    <button onClick={increment}>{count}</button>
  )
)

Implementation

This one is simple: add a second function argument to connect(), then we just call it when constructing the class and pass it the store. That method returns us an object we can pass down as handler props.

export default function connect(mapToProps, createActions) {
  return Child =>
    class Connected extends React.Component {
      // pass the store to createActions() and get back our bound actions:
      actions = createActions(this.context.store)
      // ...
      render() {
        return <Child store={this.context.store} {...this.actions} {...this.props} {...this.state} />
      }

Testing Example

Since our straw-man was testing, here's how you'd test with the above changes:

import createActions from './actions'
import createStore from 'redux-zero'

// we're importing lots still, but it's all (repeatedly) instantiable.
// Because we instantiated it, we know it's clean (no need to "reset").
let store = createStore({ count: 0 })
let actions = createActions(store)
actions.increment()
expect(store.getState()).to.eql({ count: 1 })
// ^ we know nothing outside could have affected this, it's our test store.

2. Auto-binding an actions map

This one is nice - instead of actions mutating the store directly, they get "bound" to the store by connect(). Now all they have to do is accept (state, ...args) as arguments and return a new state - everything else is automated.

It's interesting to note - redux exposes a bindActionCreators() method that does this, but it also includes this binding behavior by default when passing an object 2nd argument to connect().

import { createStore, Provider, connect } from 'redux-zero'
export default () => <Provider store={createStore()}><App /></Provider>

const mapStateToProps = Object  // or whatever

// Actions are just pure functions that return a derivative state.
// Importantly, they don't need "hardwired" access to the store.
// Any arguments passed to the bound action are passed after state
const increment = ({ count }) => ({ count: count+1 })

const actions = { increment }

const App = connect(mapStateToProps, actions)(
  ({ count, increment }) => (
    <button onClick={increment}>{count}</button>
  )
)

Implementation

This adds one small step to connect() - in Connected, we'd need to loop over the passed actions and create their store-bound proxies, then store the proxy function mapping as a property of the class. This could either happen in the constructor, as an instance property, or within componentWillMount.

function bindActions(actions, store) {
  let bound = {}
  for (let name in actions) {
    bound[name] = (...args) => {
      store.setState( actions[name](store.getState(), ...args) )
    }
  }
  return bound
}

export default function connect(mapToProps, actions) {
  return Child =>
    class Connected extends React.Component {
      // bind the pure actions to our store:
      actions = bindActions(actions, this.context.store)
      // ...
      render() {
        return <Child store={this.context.store} {...this.actions} {...this.props} {...this.state} />
      }

Testing Example

The benefits of this approach get pretty clear when you look at how to test things. Since actions are now just pure functions that accept the current state and return a new one, they're easy to test in complete isolation:

import { increment, decrement } from './actions'  // not tied to a component

// no store instance needed
expect( increment({ count:0 }) ).to.eql({ count: 1 });
// ^ pure tests are almost pointlessly easy

One caveat with this approach is that async actions become a little harder. With option #1, actions can invoke store.setState() in response to async stuff, it'll just always be available. With option #2, there'd need to be some way to access the store later on. Another alternative would be to change bindActions() to handle Promise return values from actions.


Hope this is useful, I'd love to see an option like this make its way into redux-zero!

React connect decorator prevents hot module reloading

The react/connect decorator prevents webpack and react-native hot module reloading. As far as I'm aware, React HMR doesn't work with pure functional components. This is an easy fix, simply change the innermost return value of connect() to a class instead of a function:

export default function connect(mapToProps, actions = {}) {
  return Child => (
    class ConnectWrapper extends React.Component<any> {
      render() {
        const { props } = this

        return (
          <Connect {...props} mapToProps={mapToProps} actions={actions}>
            {mappedProps => <Child {...mappedProps} {...props} />}
          </Connect>
        )
      }
    }
  )
}

I think this would go a long way towards adoption of redux-zero, which I absolutely love!

Passing parameters on actions with Render Props

In #53, we discussed ways to pass parameters (payload) in the actions.

For example, if we want an increment action, with a dynamic value to be incremented:

<button onClick={() => increment(10)}>Increment 10</button>

With our current code base, this can be easily done by simple using the second argument of the increment function, like this:

const actions = store => ({
  increment: (state, payload) => ({ count: state.count + payload }),
});

There's just one problem: this only works for the HOC Connect. For some reason this is not working with the render props connect function.

how to get ownProps?

<Provider store={store}>
    <Counter color="blue" />
</Provider>

if i pass a prop color="blue" to the connected component it's not accessible inside Counter component as a prop. Only props that you return from mapToProps function are passed as constructor props.
Redux passes properties as ownProps as the second argument of mapToProps function.

Is it missing from redux-zero or am i doing something wrong ?

Add documentation of action arguments

I had to explore the source code to find that action arguments come from the second parameter (and later) after state

const increment = state => ({ count: state.count + 1 })
const incrementBy = (state, amount) => ({ count: state.count + amount })
//                          ^ this


// later
props.increment()
props.incrementBy(10 /* amount */)

Yeah, I know it's simple and I did not see any problems with choice of API (although I prefer it curried), but it's not intuitive. It's not something anyone can easily guess by.

I think that a small example of these in readme, such as incrementBy, would help people with this same problem/doubt.

Maybe we can add some other action in readme example. Suggestions?

Middleware?

First off, I love the concept and the simplicity of it. I often found myself annoyed with reducers because the project is so small.

With that said, things like redux-sagas and redux-observables seem to offset the need for reducers. Wonder would would be a simple way to introduce a form of middleware without the bloat. My first inclination is composing actions, but not sure if you had a better idea in mind?

I guess I'm looking for a way to do async actions.

SSR?

Really cool looking project. Does this work in a server rendered react app?

Adding a function to access specific member of the state

Right now to access a deep member of the state while keeping immutability looks like :

const actions = store => ({
  setSpecificValue: state => value => ({ 
    ...state, 
    specific: {
      ...specific,
      value
    } 
  }),
});

it would simplify it more if we had some utility functions for us to use like this :

const actions = store => ({
  setSpecificValue: editStoreWithState('specific.value', (state) => (value) => value ),
  setSpecificValue: editStore('specific.value', (value) => value ),
});

What do you think ?

Export bindActions function

Hey,

My use case is the following: I have a library that uses Preact and exposes a public interface on the window object. The library itself creates some components and allows the webpage to interact with them through functions on window.Library.

For instance, calling window.Library.openDialog() should render a Preact component.
I need to execute actions from that openDialog function that is not connected to the store through a Connect component. Effectively, I am looking for bound actions that I can run from outside the Preact/Redux zero environment.

I am thinking that you could export the bindActions function and I can create those bound actions when I need to.

Any opinion on that? Let me know if you think there is a better approach to this.

Thanks a lot for this great library!
Jawad

connect not available for preact (only React)

This is a tricky request to report in terms of SEO :p

So there this connect and Connect.

connect you can wrapp on top of the entire component, allowing it's methods to be available in the constructor and any function within.

Connect only wraps the component's HTML, making actions and state unavailable in the constructor or other functions.

pass payload

Hello guys,
I try redux zero with a input type text but I can't get the payload when I use the onChange event. it's normal or a bug?

Thanks

Split the project

Right now the project is coupled with React.
We should split the project so that we can have React, Preact, Angular and Vue bindings, for example.

redux question, Shared state?

(I'm pretty new at redux, about one week)

I have two components, both need to render a list of items.

One third component dispatch an action to update the item list which lives on the store.

When the store get updated two listeners invoke update func in Connect component (which wraps each component)

image

The problem is that those components only render when there is no shallowEqual between the actual props and the current state. But the current state is shared! meaning that only the first component will be rendered!

Im doing something wrong!? (yes, but what! hehe)

Computed equivalent?

Great project. I frequently use MobX computed values to have derived values from the mutable state.

Can you recommend or explain the equivalent to derived values using redux-zero?
Should I store computed values in store state? Or use listeners in some way?

Thanks

Add time travel

Redux comes with a time travel feature. For them, it's kind easy to do it (immutability).

For us not so much, but I think it's possible.

How do you work with side effects?

for example I have three actions that fetch data via HTTP: fetch, fetchSuccess, fetchError

is something like the following "ok"?

const actions = store => ({
    fetch: state => {
        const stateUpdate = { ...state, loading: true };
        fetchFromApi().then(data => store.fetchSuccess(stateUpdate, data), err => store.fetchError(stateUpdate, err));
        return stateUpdate;
    },
    fetchSuccess: (state, payload) => ({ ...state, data: payload, loading: false }),
    fetchError: (state, payload) => ({ ...state, loading: false, error: payload }),
});

Render props

With the big push to render props wonder if it would be a good idea to add a render-prop variant. Something like this...

import React from "react";
import { connect } from "redux-zero";

import { increment, decrement } from "./actions";

const mapToProps = ({ count }) => ({ count });

export default () => (
    <Connect mapToProps={mapToProps}>
        {({ count }) =>
            <div>
                <h1>{count}</h1>
                <div>
                    <button onClick={increment}>increment</button>
                    <button onClick={decrement}>decrement</button>
                </div>
            </div>
        }
    </Connect>
);

Update Svelte example

Right now, Counter.html is doing this:

import { connect, getActions  }  from '../../../../../src/svelte';

But it should be doing this:

import { connect, getActions  }  from 'redux-zero/svelte';

@Kiho, could you please change this and check if everything is working?
You should probably update the npm version from the example to 4.3.0

weird TypeError with TypeScript on createStore func

Given the following implementation

image

I got this err: Uncaught TypeError: redux_zero_1.default is not a function

I look a little bit on the bundle settings and I found that the main file which is served by default isn't on UMD format:

"main": "dist/redux-zero.js",

because of this:

image

I don't have too much knowledge about this. I'll keep looking but I need your help on this.

bug: state twice, no payload

Version 4.8.1

Curried functions

increment: state => payload => state === payload
//=> true

Multiple parameters work fine

increment: (state, payload) => state === payload
//=> false

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.