Svelte Redux
Connect svelte components to a redux store.
Install
npm i svelte-redux
Usage
Connect the store
Assuming you already have a store set up, you need to connect it to your svelte component. You do this like so:
store: // ...;
If you've used redux with react, this should be quite familiar.
Map the state
The mapStateToData
property is a function that, given the current state, returns the data you want to consume in this component.
In this very simplistic example, our whole state is just a number (we're building a simple counter) so you might map it as below:
const mapStateToData = { return count: state ;};
Using the data
Now that we've mapped our state to count
, we can access it in the template like you would with local state, however it is prepended with a $
.
Clicked {{$count}} times
Dispatching actions
In order to dispatch actions, you must first map a dispatch function to the store.
const mapDispatchToStore = { return ;};
And now we can access these functions in the template via the store
+-
Optimisations
At this point everything should be working, there are however a few things we can change for convenience.
The mapDispatchToStore
function is quite verbose given the simple goal so we can instead use the shorthand:
const mapDispatchToStore = type: 'INCREMENT' type: 'DECREMENT' ;
Passing store to connect every time is slightly inconvenient and requires all your components to know about store
.
We can use the bindConnect
to make this slightly nicer.
const connect = ; // ... store: ;
And now we can use this connect function instead of the one imported from svelte-redux
Full Example
store.js
;; const store = ; const connect = ;
Counter.html
Clicked {{$count}} times+-