Gathering detailed insights and metrics for react-context-api-store
Gathering detailed insights and metrics for react-context-api-store
Gathering detailed insights and metrics for react-context-api-store
Gathering detailed insights and metrics for react-context-api-store
Seemless, lightweight, state management library that supports async actions and state persisting out of the box. Inspired by Redux and Vuex. Built on top of React's context api.
npm install react-context-api-store
Typescript
Module System
Node Version
NPM Version
JavaScript (98.04%)
HTML (1.96%)
Total Downloads
0
Last Day
0
Last Week
0
Last Month
0
Last Year
0
MIT License
4 Stars
41 Commits
2 Branches
1 Contributors
Updated on Jan 28, 2023
Latest Version
1.0.16
Package Id
react-context-api-store@1.0.16
Unpacked Size
514.12 kB
Size
86.02 kB
File Count
5
NPM Version
6.4.1
Node Version
10.10.0
Cumulative downloads
Total Downloads
Last Day
0%
NaN
Compared to previous day
Last Week
0%
NaN
Compared to previous week
Last Month
0%
NaN
Compared to previous month
Last Year
0%
NaN
Compared to previous year
2
16
Archived in favor of react-fluxible. Please migrate.
Seemless, lightweight, state management library that supports async actions and persistent states out of the box. Inspired by Redux and Vuex. Built on top of React's context api.
6.0kb transpiled. Not minified. Not compressed. Not uglified.
https://aprilmintacpineda.github.io/react-context-api-store/#/
npm install react-context-api-store
yarn add react-context-api-store
Usage is the same as with redux. Except I used React's new Context API in version 16.3.0. I also simplified store creation, action definition, and async action handing. If you've used Redux and Vuex in the past, everything here will be familiar to you.
Make sure to read and understand all the notes here after as they convey a very important message.
Provider
First, import react-context-api-store
as Provider
. The Provider is a component that accepts a prop called store
. You would use this component as your top most component.
1import React from 'react'; 2import { render } from 'react-dom'; 3import { BrowserRouter, Route, Link, Switch } from 'react-router-dom'; 4import Provider from 'react-context-api-store'; 5 6class App extends React.Component { 7 render () { 8 return ( 9 <Provider store={store}> 10 <BrowserRouter> 11 <div> 12 <ul> 13 <li> 14 <Link to="/todos">Todos</Link> 15 </li> 16 <li> 17 <Link to="/">Home</Link> 18 </li> 19 </ul> 20 <Switch> 21 { 22 routes.map((route, i) => <Route key={i} {...route} />) 23 } 24 </Switch> 25 </div> 26 </BrowserRouter> 27 </Provider> 28 ); 29 } 30} 31 32render( 33 <App />, 34 document.querySelector('#app') 35);
store
The store is simply a JS object where your global states would live.
1{ 2 userState: { 3 username: defaultUsername 4 }, 5 todos: [...defaultTodos], 6 anotherState: valueHere, 7 oneMoreState: oneMoreValue 8};
Then you pass this as the store
prop to the provider.
The provider always assume that the store is an object. No checks were added to minimize the file size. Making sure that you pass an object as the store
is up to you.
Works the same way as with redux, with a little bit of change. You import { connect }
from the react-context-api-store
package. Connect is an HOC that wraps your component with the Provider.Consumer
and passes all the states and actions to the component as properties.
Connect
accepts two parameters. The first parameter is a callback function
that will receive the store's current state
. It should return an object that maps all the states that you want the component to have.
connect
always assume that the first parameter is a function. No checks were added to minimize the file size.
example code
1function mapStateToProps (state => { 2 console.log(state); 3 4 return { 5 // .. all the state that I want 6 user: state.user, 7 todos: state.todos 8 } 9})
The second parameter is an object containing all the functions that will serve as the action. This is typically what you call when the user clicks a button or a particular event occured. The action will receive the original parameters given to it, except it will receive an object as the first parameter, this object is provided by the dispatcher
. The object contains two things, (1) the store's state and (2) a function called updateStore
. The updateStore
function is what you call when you want to update the state, you need to give it an object of the states that you want to update, the rest that you did not touch will remain unchanged and intact.
connect
always assume that the second parameter is an object. No checks were added to minimize the file size.dispatcher
always assume that all actions are functions. No checks were added to minimize the file size.store.updateStore
always assume that you'll give it an object as the first parameter. No checks were added to minimize the file size.example code
1// somewhere in your component 2<input 3 type="checkbox" 4 checked={todo.isDone} 5 onChange={e => this.props.updateTodoDone(e.target.checked, todo.value, i)} 6/> 7 8// the second parameter 9const actions = { 10 updateTodoDone (store, isDone, targetValue, targetIndex) { 11 store.updateStore({ 12 todos: store.state.todos.map((todo, todoIndex) => { 13 if (todo.value != targetValue || todoIndex != targetIndex) return todo; 14 15 return { 16 ...todo, 17 isDone 18 }; 19 }) 20 }); 21 } 22}
Over all, you'll have something like this:
1import React from 'react'; 2import PropTypes from 'prop-types'; 3import { connect } from 'react-context-api-store'; 4 5/** 6 * in this example, all the action handlers are in the 7 * ../store/index.js but it does matter where you store them, 8 * they are just functions that when executed gains access to the 9 * store. 10 */ 11import { updateTodoDone, deleteTodo, addTodo } from '../store'; 12 13class Todos extends React.Component { 14 state = { 15 newTodoValue: '' 16 } 17 18 handleNewTodoSubmit = (e) => { 19 e.preventDefault(); 20 21 return this.props.addTodo(this.state.newTodoValue, () => this.setState({ 22 newTodoValue: '' 23 })); 24 } 25 26 addTodoForm = () => { 27 return ( 28 <form onSubmit={this.handleNewTodoSubmit}> 29 <input 30 type="text" 31 value={this.state.newTodoValue} 32 onChange={e => this.setState({ 33 newTodoValue: e.target.value 34 })} 35 /> 36 <input type="submit" value="Add todo" /> 37 </form> 38 ); 39 } 40 41 render () { 42 if (!this.props.todos.length) { 43 return ( 44 <div> 45 {this.addTodoForm()} 46 <h1>Hi {this.props.userState.username}, your todo list is empty.</h1> 47 </div> 48 ); 49 } 50 51 return ( 52 <div> 53 {this.addTodoForm()} 54 <h1>Hi {this.props.userState.username}, {'here\'s your todo list'}.</h1> 55 { 56 this.props.todos.map((todo, i) => 57 <div key={i} style={{ marginBottom: '10px' }}> 58 <span 59 style={{ cursor: 'pointer', userSelect: 'none', backgroundColor: 'red', color: 'white', marginRight: '2px', borderRadius: '2px', padding: '1px' }} 60 onClick={() => this.props.deleteTodo(todo.value, i)}>x</span> 61 <label style={{ cursor: 'pointer', userSelect: 'none' }}> 62 <input 63 type="checkbox" 64 checked={todo.isDone} 65 onChange={e => this.props.updateTodoDone(e.target.checked, todo.value, i)} 66 /> 67 { 68 todo.isDone? 69 <span style={{ color: 'red', textDecoration: 'line-through' }}> 70 <span style={{ color: 'gray' }}>{todo.value}</span> 71 </span> 72 : <span>{todo.value}</span> 73 } 74 </label> 75 </div> 76 ) 77 } 78 </div> 79 ); 80 } 81} 82 83export default connect(store => ({ 84 userState: store.userState, 85 todos: store.todos 86}), { 87 updateTodoDone, 88 deleteTodo, 89 addTodo, 90 // you could also add something else here 91 anotherAction (store) { 92 /** 93 * if your action handler does not call store.updateState(); 94 * nothing will happen to the state 95 */ 96 console.log(store); 97 } 98})(Todos);
store.updateStore
store.updateStore
has a second optional parameter which should be a function
that will be run as callback of setState
. This callback will receive the store's update state as it's only parameter. Please see react's docs about setState
.
The package itself does not care how you handle this, you can use async/await
if you like or stick to the chained .then
of promises. But don't use generator functions as the store package was not equipped with it and supporting it is not an option because it would defeat the whole purpose of this library.
example code
1function myStateHandler (store, data) {
2 store.updateState({
3 aState: {
4 ...store.state.aState,
5 loading: true
6 }
7 });
8
9 fetch('/somewhere')
10 .then(response => response.json())
11 .then(response => {
12 // do something with the response
13
14 store.updateState({
15 aState: {
16 ...store.state.aState,
17 loading: false,
18 data: { ...response.data }
19 }
20 });
21 });
22}
If you want to persist states, just provide a second property called persist
which is an object that has the following shape:
1{ 2 storage: AsyncStorage, // the storage of where to save the state 3 statesToPersist: savedStore => { 4 // do whatever you need to do here 5 // then return the states that you want to save. 6 // NOTE: This is not strict, meaning, you can even 7 // create a new state here and it will still be saved 8 return { 9 someState: { ...savedStore.someState }, 10 anotherState: [ ...savedStore.anotherState ], 11 someValue: savedStore.someValue 12 } 13 } 14}
example snippet
1<Provider store={store} persist={{ 2 storage: window.localStorage, 3 statesToPersist (savedStore) { 4 return { ...savedStore }; 5 } 6}}>
In this case I'm passing in the window.localStorage
as the storage but you are free to use whatever storage you need but it must have the following methods:
getItem
which receives the key
as the first parameter.setItem
which receives the key
as the first parameter and value
as the second parameter.removeItem
which receives the key
as the first parameter.No vulnerabilities found.
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 0/30 approved changesets -- score normalized to 0
Reason
no SAST tool detected
Details
Reason
project is archived
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
106 existing vulnerabilities detected
Details
Score
Last Scanned on 2025-07-14
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More