orac
v0.1.6
Published
Simple to use, scalable, no trills global state. Non opinionated
Downloads
4
Maintainers
Readme
Orac
Simple to use, scalable, no trills global state for React. Non opinionated.
npm install orac
Install Orac
npm install orac
Create a file named store.js and add this code:
import { createStore } from 'orac';
const initialState = {
title: 'Orac Global State',
count: 0,
};
export const useStore = createStore((get, set) => {
return {
state: {
...initialState,
},
setState: (payload) =>
set((store) => ({
...store,
...payload,
})),
};
});
Add this code to your main App
import React from 'react';
import { useStore } from './store';
function App() {
const Count = () => {
const { state } = useStore();
const { count, title } = state;
return (
<>
<h1>{title}</h1>
<h2>{count}</h2>
</>
);
};
const Controls = () => {
const { state, setState } = useStore();
const { count } = state;
const updateCount = (payload) => {
setState({
state: {
...state,
count: payload,
},
});
};
return (
<h2>
<button onClick={() => updateCount(count + 1)}>+</button>
<button onClick={() => updateCount(count - 1)}>-</button>
</h2>
);
};
return (
<div>
<Count />
<Controls />
</div>
);
}
export default App;
Using a reducer
If you prefer to use a reducer then you could create a dispatch method. This can be achieved by passing in the reducer, state and action. Create a file named store.js or modify the existing file.
import { createStore } from 'orac';
const initialState = {
title: 'Orac Global State',
count: 0,
};
export const useStore = createStore((get, set) => {
return {
state: {
...initialState,
},
dispatch: (reducer, state, action) => {
set((store) => ({
...store,
...reducer(state, action),
}));
},
};
});
Add this code to your main App replacing all previous code.
import React from 'react';
import { useStore } from './stores';
function App() {
const Count = () => {
const { state } = useStore();
const { count, title } = state;
return (
<>
<h1>{title}</h1>
<h2>{count}</h2>
</>
);
};
const countReducer = (state, action) => {
switch (action.type) {
case 'increment':
return {
state: {
...state,
count: action.payload,
},
};
case 'decrement':
return {
state: {
...state,
count: action.payload,
},
};
default:
return state;
}
};
const Controls = () => {
const { state, dispatch } = useStore();
const { count } = state;
return (
<h2>
<button
onClick={() =>
dispatch(countReducer, state, {
type: 'increment',
payload: count + 1,
})
}
>
+
</button>
<button
onClick={() =>
dispatch(countReducer, state, {
type: 'decrement',
payload: count - 1,
})
}
>
-
</button>
</h2>
);
};
return (
<div>
<Count />
<Controls />
</div>
);
}
export default App;