adding logic to redux reducer to persist state - react-redux

I am working with a react/redux learning project, where I'm building components to host headless CMS content. One part of the application is a dropdown that will select the content from all available content channels in the source CMS.
This works on the first pass, but when I navigate to another page (ie, the detail of a single CMS content item - the first page displays multiple items in a grid) it resets the state back to an initial (empty) variable.
The component is below:
import { FETCH_CHANNELS } from '../actions/types';
// set the initial state first
const initialState = {
isLoading: true,
data: [],
error: ""
}
// set the state depending on the dispatch coming in
const channelsReducer = (state = initialState, action) => {
switch(action.type) {
case FETCH_CHANNELS:
// reduce the returned state down to an array of options
// filter here to limit to searchable only
const activeChannels = [];
action.payload['channels'].forEach( el => {
if(el.isChannelSearchable) {
let singleItem = {
key: el.channelId,
value: el.channelId,
text: el.channelName,
type: el.channelType
}
activeChannels.push(singleItem);
}
});
return {...state, data: activeChannels, isLoading: false};
case "ERROR":
return {...state, error: action.msg};
default:
return state;
}
}
export default channelsReducer;
My issue here (as I see it), is the initialisation of the initialState constant at the beginning, everytime that the component is refreshed, it is set to empty again. Makes sense.
How can I persist the state that is returned in the FETCH_CHANNELS case (that action is a call to a back end api that returns all channels) so that upon the component remounting it still retains it's state?
Not sure if I have to either (quite possibly none of these are correct):
Attempt with some logic in the front end component that is calling this action, to not call it if data already exists?
Create another piece of state in the redux store and update that state from the front end component once a value from the drop down has been selected?
or 3. Try and handle it here with setting a variable in the reducer and logic to return that if necessary?
Like I said, I'm building this to try and learn a bit about react and redux, but i'm really not sure what the way to handle this is...

update, as suspected... neither of those options were correct. I was not calling the link correctly in the component generating the click event to drill into the detail content item. Implementing Link from react-router-dom was the right way to handle this.

Related

How do you get data back from a react-redux store?

Using React-Redux
I have a select list that when the user chooses one of the options, a item is created and placed in the database (if it matters, the reason its a select box is that there are multiple variations of the same item and what variation is important).
This is working correctly.
My problem is that I am not sure how I can get the id of the new item out of the redux store.
And just for chuckles, the prior developer set all this up with sagas. So I am still coming up to speed on how it all works together.
So when the select box is checked, the function checkFunction is called that calls the function createItem in the saga file. These functions are below:
in Repositories.jsx
checkFunction = (data) => {
const {createItem} = this.props;
// data holds the info that we need to send to the action
const created = createItem(data);
// once data comes back, redirect the user ot the details of the created item
// need id of created item
// navigateTo(`/item-details/${created.id}`);
}
in Repositories.saga.js
export function* createItem(action) {
try {
const {payload: newItem} = action;
// call api to create item
const created = yield call(requestAPI.post, ITEMS_URL, newItem);
// send message that its been done
yield put(actions.repositories.createItem.ok(created));
// send message to refresh item list
yield put(actions.inventories.fetchItems.start());
} catch (e) {
yield put(actions.repositories.createItem.fail(e));
}
}
I don't understand how to return the id of the created item once its created. I feel like I am missing something basic here. Can anyone point me in the right direction?
Actually getting data from saga back to react component is not trivial. There are multiple approaches to do what you need although each has its downside.
1. Call navigateTo in the saga.
export function* createItem(action) {
...
const created = yield call(requestAPI.post, ITEMS_URL, newItem);
yield call(navigateTo, `/item-details/${created.id}`)
}
This would be my recommended solution if you can get the navigateTo function into the saga. Navigation is a side effect and sagas are there to deal with side effects. Make sure to use the call effect, changing the url by directly calling the function can lead to some issues.
2. Store the latest created item id in redux store
In your reducer, when action actions.repositories.createItem.ok(created) is dispatched, store the created item info and then send the latest created item to the component. Finally you can use componentDidUpdate or useEffect to call navigateTo when the prop changes.
render() {
const created = Redux.useSelector(state => state.created);
useEffect(() => navigateTo(`/item-details/${created.id}`), [created])
...
}
This has the disadvantage that the component will rerender becuase of the changed created value.
3. Send callback in the createItem action
You can put a function into your action and then call it from the saga and essentially using it as a callback.
Component:
checkFunction = (data) => {
const {createItem} = this.props;
// data holds the info that we need to send to the action
const created = createItem(data, (created) => {
navigateTo(`/item-details/${created.id}`);
});
}
Saga:
export function* createItem(action) {
...
const created = yield call(requestAPI.post, ITEMS_URL, newItem);
action.callback(created)
...
}
The problem with this approach is that functions are not serializable and so you ideally should avoid them in your actions. Also, technically, there could be multiple sagas handling the same action and then it gets kind of confusing who should call the callback.

BehaviorSubject send the same state reference to all subscribers

In our Single Page Application we've developed a centralized store class that uses an RxJS behavior subject to handle the state of our application and all its mutation. Several components in our application are subscribing to our store's behavior subject in order to receive any update to current application state. This state is then bound to UI so that whenever state changes, UI reflect those changes. Whenever a component wants to change a part of the state, we call a function exposed by our store that does the required work and updates the state calling next on the behavior subject. So far nothing special. (We're using Aurelia as a framework which performs 2 way binding)
The issue we are facing is that as soon as a component changes it's local state variable it receives from the store, other components gets updated even if next() wasn't called on the subejct itself.
We also tried to subscribe on an observable version of the subject since observable are supposed to send a different copy of the data to all subscriber but looks like it's not the case.
Looks like all subject subscriber are receiving a reference of the object stored in the behavior subject.
import { BehaviorSubject, of } from 'rxjs';
const initialState = {
data: {
id: 1,
description: 'initial'
}
}
const subject = new BehaviorSubject(initialState);
const observable = subject.asObservable();
let stateFromSubject; //Result after subscription to subject
let stateFromObservable; //Result after subscription to observable
subject.subscribe((val) => {
console.log(`**Received ${val.data.id} from subject`);
stateFromSubject = val;
});
observable.subscribe((val) => {
console.log(`**Received ${val.data.id} from observable`);
stateFromObservable = val;
});
stateFromSubject.data.id = 2;
// Both stateFromObservable and subject.getValue() now have a id of 2.
// next() wasn't called on the subject but its state got changed anyway
stateFromObservable.data.id = 3;
// Since observable aren't bi-directional I thought this would be a possible solution but same applies and all variable now shows 3
I've made a stackblitz with the code above.
https://stackblitz.com/edit/rxjs-bhkd5n
The only workaround we have so far is to clone the sate in some of our subscriber where we support edition through binding like follow:
observable.subscribe((val) => {
stateFromObservable = JSON.parse(JSON.stringify(val));
});
But this feels more like a hack than a real solution. There must be a better way...
Yes, all subscribers receive the same instance of the object in the behavior subject, that is how behavior subjects work. If you are going to mutate the objects you need to clone them.
I use this function to clone my objects I am going to bind to Angular forms
const clone = obj =>
Array.isArray(obj)
? obj.map(item => clone(item))
: obj instanceof Date
? new Date(obj.getTime())
: obj && typeof obj === 'object'
? Object.getOwnPropertyNames(obj).reduce((o, prop) => {
o[prop] = clone(obj[prop]);
return o;
}, {})
: obj;
So if you have an observable data$ you can create an observable clone$ where subscribers to that observable get a clone that can be mutated without affecting other components.
clone$ = data$.pipe(map(data => clone(data)));
So components that are just displaying data can subscribe to data$ for efficiency and ones that will mutate the data can subscribe to clone$.
Have a read on my library for Angular https://github.com/adriandavidbrand/ngx-rxcache and my article on it https://medium.com/#adrianbrand/angular-state-management-with-rxcache-468a865fc3fb it goes into the need to clone objects so we don't mutate data we bind to forms.
It sounds like the goals of your store are the same as my Angular state management library. It might give you some ideas.
I am not familar with Aurelia or if it has pipes but that clone function is available in the store with exposing my data with a clone$ observable and in the templates with a clone pipe that can be used like
data$ | clone as data
The important part is knowing when to clone and not to clone. You only need to clone if the data is going to be mutated. It would be really inefficient to clone an array of data that is only going to be displayed in a grid.
The only workaround we have so far is to clone the state in some of our subscriber where we support edition through binding like follow:
I don't think I can answer that without rewriting your store.
const initialState = {
data: {
id: 1,
description: 'initial'
}
}
That state object has deeply structured data. Everytime you need to mutate the state the object needs to be reconstructed.
Alternatively,
const initialState = {
1: {id: 1, description: 'initial'},
2: {id: 2, description: 'initial'},
3: {id: 3, description: 'initial'},
_index: [1, 2, 3]
};
That is about as deep of a state object that I would create. Use a key/value pair to map between IDs and the object values. You can now write selectors easily.
function getById(id: number): Observable<any> {
return subject.pipe(
map(state => state[id]),
distinctUntilChanged()
);
}
function getIds(): Observable<number[]> {
return subject.pipe(
map(state => state._index),
distinctUntilChanged()
);
}
When you want change a data object. You have to reconstruct the state and also set the data.
function append(data: Object) {
const state = subject.value;
subject.next({...state, [data.id]: Object.freeze(data), _index: [...state._index, data.id]});
}
function remove(id: number) {
const state = {...subject.value};
delete state[id];
subject.next({...state, _index: state._index.filter(x => x !== id)});
}
Once you have that done. You should freeze downstream consumers of your state object.
const subject = new BehaviorSubject(initialState);
function getStore(): Observable<any> {
return subject.pipe(
map(obj => Object.freeze(obj))
);
}
function getById(id: number): Observable<any> {
return getStore().pipe(
map(state => state[id]),
distinctUntilChanged()
);
}
function getIds(): Observable<number[]> {
return getStore().pipe(
map(state => state._index),
distinctUntilChanged()
);
}
Later when you do something like this:
stateFromSubject.data.id = 2;
You'll get a run-time error.
FYI: The above is written in TypeScript
The big logical issue with your example is that the object forwarded by the subject is actually a single object reference. RxJS doesn't do anything out of the box to create clones for you, and that is fine otherwise it would result in unnecessary operations by default if they aren't needed.
So while you can clone the value received by the subscribers, you're still not save for access of BehaviorSubject.getValue(), which would return the original reference. Besides that having same refs for parts of your state is actually beneficial in lots of ways as e.g arrays can be re-used for multiple displaying components vs having to rebuild them from scratch.
What you want to do instead is to leverage a single-source-of-truth pattern, similar to Redux, where instead of making sure that subscribers get clones, you're treating your state as immutable object. That means every modification results in a new state. That further means you should restrict modifications to actions, (actions + reducers in Redux) which construct a new state of the current plus the necessary changes and return the new copy.
Now all of that might sound like a lot of work but you should take a look at the official Aurelia Store Plugin, which is sharing pretty much the same concept as you have plus making sure that best ideas of Redux are brought over to the world of Aurelia.

nuxt.js unable to refer store value?

I am using nuxt.js to implement a online commerce.
I am doing something like the below to check user is logged in or not.
In my header, would like to determine display some part(like point, mypage button ... etc) or not by a value of isSigned, which is boolean type variable. In my case, I use computed function in a template.
In my vuex store, would like to update session(action-mutation) in nuxtServerInit so I could reassign values from the API server.
Here is a part of header code, it is computed to check isSign.
computed : {
isSign : function () {
console.log('HEADER COMPUTED EXECUTED ISSIGNED', this.$store.state.session, new Date().getTime());
return this.$store.state.session.signed;
}
}
Ans here is corresponding store code, in mutation.
export const mutations = {
sessionUpdateSeccess : function (state, payload) {
console.log('SESSION UPDATE SECCESS :: ', state, payload)
state.signed = payload.signed;
console.log('SESSION UPDATE SECCESS END :: ', state, payload, new Date().getTime())
}
}
The mutations code works fine, but in header component, signed value is still true, even though state has changed.
So I print the end time of each process.
mutations : 1540520171177
computed : 1540520170690
Until far, I reached a conclusion that I should not refer store value in computed.
I would like to know common way to check user session in nuxt. Thanks.

reducer goes into a loop when returning a new array created from state

I am using react-redux 5.0.6 and have a reducer with the following code:
export default (state = [], action) => {
switch(action.type) {
case 'ADD_ENGAGEMENT':
let newArr = state.slice();
newArr.push(action.payload);
return newArr;
case 'UPDATE_ENGAGEMENT':
console.info('UPDATE_ENGAGEMENT')
return state.slice();
// return state;
default:
return state;
}}
The issue occurs within the 'UPDATE_ENGAGEMENT' case -- the actual logic has been removed and replaced with the simplest example to demonstrate the problem.
When a new array created from state via state.slice() is returned, a loop is triggered, causing the action to be dispatched until an 'Uncaught RangeError: Maximum call stack size exceeded' error is raised. Screenshot of the browser console during the issue's occurrence
The issue is not limited to 'slice()' and occurs whenever an array containing any element of state is returned e.g. return [state[0]].
When the original state is returned, the issue does not occur.
I am completely baffled by this behavior and cannot fathom how anything in my application could be causing it. Any insight would be immensely appreciated.
To provide some additional context, below is the code involved in the action's being dispatched:
componentWillReceiveProps(newProps) {
let engagementTemplateData = newProps.selectedEngagementTemplate;
let engagements = newProps.engagements;
if (engagementTemplateData && engagementTemplateData.engagementUuid === this.props.uuid) {
let template = engagementTemplateData.template;
this.updateEngagementTemplate(template);
}
}
updateEngagementTemplate(template) {
let url = `/engagements/${this.props.uuid}`;
let requestHelper = new AjaxRequestHelper(url);
let data = {template_uuid: template.uuid};
this.props.updateEngagement({uuid: this.props.uuid, template: template});
// requestHelper.put(data, response => {
// this.props.updateEngagement({uuid: this.props.uuid, template: template});
// });
}
Basically, the function which triggers the action is called in componentWillReceiveProps as a result of another action. However, I am not sure how helpful this information is, since the reducer itself appears to be working properly when responding to the action -- it's just that something strange is happening with the state, which prevents its elements from being returned.
From the sounds of it (and from the react callstack), I imagine the array changing (by reference) in the store is being picked up by a react component props, which in its should/did update logic is calling that action without a guard. This is often a mistake when calling actions or setState from componentDidMount/Update -
It works when the original state is returned as the reference is the same so React does not continue with its update logic, and hence call your code that publishes the action
Consider this pure component that will cause an endless loop with your reducer code...
export interface IMyProps {
myArray: any[],
updateEngagementAction: () => void
}
export class EndlessLoopFromArrayPropComponent extends React.PureComponent<IMyProps> {
// PureComponent compares props by reference only
// so will cause update if this.props.myArray reference has changed in store (ie from slice())
render() {
// blahblah...
}
componentDidUpdate() {
// this will call action after every update
// as every time this action is called it passes in a new reference this.props.myArray to this component
// so react will update this component again, causing the action to be called again
// ... endless loop
this.props.updateEngagementAction()
}
}
Your implementation will differ of course but this will be the principal that is causing it to happen, so you need to add a guard condition in whatever code path leads to your action being called.
For the code above you would need to check an escape condition before sending the action OR implement shouldComponentUpdate or similar to do deeper prop comparison to guard against unnecessary updates, and hence it would not reach that action code in the componentDidUpdate method
EDIT This was written before the react code was added to question. Here I refer to the action being called without guard in componentDidUpdate however the same applies when called in any of the other lifecycle methods triggered by a prop change, in this case componentWillRecieveProps. To be fair it did have a guard already, but never returned false as a more in-depth props check was needed, so caused a loop to occur via willreceive -> true -> action -> reducer -> willreceive -> true ........

Should I filter within my flux stores?

This is essentially a matter of best practices for sync vs. async operations in the store/view.
I'm attempting to build a real-time search field for a list of items.
In my current implementation, I request all the items from my server and save them to a store. When a user enters characters into the search field, the view filters the items using the .filter() native function. Unfortunately, this causes some delay (due to the number of items and the complexity of the filter) before the next rendering (which includes the keypressed character displaying in the search field).
My question is: should I instead call an action to initialize the filtering of the items in the store, and update whenever the store is complete? Then, in the meantime, I would be able to render the keypressed character before the filtered results come in.
Is there an intuitive way to prevent/abort a previous, incomplete request to filter when a new one comes in?
Edit:
Here's the new implementation:
The component/view
_onChange() {
this.setState({
items: ItemStore.getFilteredItems()
})
},
handleSearchChange(event) {
this.setState({
searchText: event.target.value,
})
ItemActions.filterItems(event.target.value)
},
render() {...}
The action
filterItems(searchTerm) {
dispatcher.dispatch({
type: FILTER_ITEMS,
searchTerm: searchTerm,
});
}
The store
var _store = {
items: [],
filteredItems: []
}
var filter = function (searchTerm) {...}
...
Dispatcher.register(function (action) {
switch (action.type) {
case FILTER_ITEMS:
filter(action.searchTerm)
ItemStore.emit(CHANGE_EVENT)
break
}
})
Edit 2:
I've ended up adding a setTimeout when dispatching within the action to make it async. I also split the list of items and the search into two different components so that the time required to re-render the list does not affect/block the search field component.
The filtering should not be blocking the keypressed character in the search field. Basically, because the filtering is a heavy operation, treat it as if it were an async HTTP event.
Here's how you should be doing in a Flux world:
Retrieve all items from the server and save them to the store
Each time you type in the search field, set the state for the input field and the component should re-render immediately (https://facebook.github.io/react/docs/forms.html#controlled-components)
At the same time as you set the state of the text, also dispatch an action to filter the results. The filtered results should be put in the store as a separate entity and updated as a result of this action.
When the store updates the filtered results, your component should have them as a prop and re-render automatically (independent of the keypress events)

Resources