Tuesday, December 31, 2019

The redux Store



The store has the following responsibilities:

    Holds application state;
    Allows access to state via getState();
    Allows state to be updated via dispatch(action);
    Registers listeners via subscribe(listener);
    Handles unregistering of listeners via the function returned by subscribe(listener).


There will only be a single store in a Redux application. When you want to split your data handling logic, you'll use reducer composition instead of many stores.


To create a store, pass all the reducers to createStore function

import { createStore } from 'redux'
import todoApp from './reducers'
const store = createStore(todoApp)


We can optionally specify the initial state as the second argument to createStore(). This is useful for hydrating the state of the client to match the state of a Redux application running on the server.

const store = createStore(todoApp, window.STATE_FROM_SERVER)

Below snippet gives could of useful infos

1. How to subscribe for the store
2. How to accèss the state directly from store
3. How to dispatch an action to the store

import {
  addTodo,
  toggleTodo,
  setVisibilityFilter,
  VisibilityFilters
} from './actions'

// Log the initial state
console.log(store.getState())

// Every time the state changes, log it
// Note that subscribe() returns a function for unregistering the listener
const unsubscribe = store.subscribe(() => console.log(store.getState()))

// Dispatch some actions
store.dispatch(addTodo('Learn about actions'))
store.dispatch(addTodo('Learn about reducers'))
store.dispatch(addTodo('Learn about store'))
store.dispatch(toggleTodo(0))
store.dispatch(toggleTodo(1))
store.dispatch(setVisibilityFilter(VisibilityFilters.SHOW_COMPLETED))

// Stop listening to state updates
unsubscribe()

References
https://redux.js.org/basics/store

No comments:

Post a Comment