ngrx, How to have a starting state from an api? - ngrx

I have my reducer with a starting state of an empty array:
folderReducer(state:Array<Folder> = [], action: Action)
I'd like to populate the starting state, so when I do
store.subscribe(s => ..)
The first item I get comes from the database. I assume the way of doing this is with ngrx/effects, but I'm not sure how.

Your store always has the initial state, that you define in the reducer-function. The initial states main purpose is to ensure that the application is able to start up and not run into any null-pointer-exceptions. And also it sets up your application to start making the first api-calls ect. - so you can think of it as a technical initial state.
If you want to fill your store with api-data on the startup, you would do that on the same way that you add/modify data during any other action - just that the action of "initially loading data" is not triggered by some user-interaction but through:
either when your root-component loads
or as part of a service in the constructor
In case you want to prevent specific components from showing anything until your API-call is done, you would have to adjust the display-components to display or hide data based on your state (e.g. by implementing a flag in your satet initialDataLoaded).

A dynamic initial state is now supported, see: https://github.com/ngrx/platform/blob/master/docs/store/api.md#initial-state-and-ahead-of-time-aot-compilation
Also see: https://github.com/ngrx/platform/issues/51
I would only do this if the database is local, otherwise the request will hold up loading of the application.

Related

redux-injectors: Using yield select in saga before reducer and saga are injected

Hello this is my first question. I am trying to set up a project where modules along with the redux and sagas will be injected into the main app, using redux-injectors. In my sagas I want to use yield select, to check if an action has updated the state and then carry on. For example, when I post an image, I want to make sure there were no errors in posting the file and then move on. I use the following function:
export const imageErrors = (state: RootState): IImagesErrorState => state.image.errors
and then in the saga.ts file I use it as such:
if (imagesErrors?.postImageError !== null) {
throw imagesErrors.postImageError
}
this works fine as long as the state.image exists in the root state from the beginning. However, how do I do that when I want to inject this state later on using useInjectReducer and useInjectSaga? I obviously get an error
Property 'image' does not exist on type 'Reducer<CombinedState<{ user: CombinedState<{ auth: IAuthState; errors: IErrorState; }>; }>, AnyAction>'.ts(2339)
So how do we handle selectors of specific pieces of state, since state does not yet include them?
Thank you so much.
Can't talk about the Typescript part of things, but in terms of architecture you've got two options.
One is the obvious - that is to add conditions or ? everywhere to avoid errors from accessing missing properties, but that can get tedious quickly.
The other probably better option is to rethink your state & application chunks. What is this saga that is accessing state that isn't existing yet? Does it need to run before you have such state? If not, let's move the saga to the same chunk as the reducer. In the opposite case, where you need the saga to be running e.g. as part of the runtime chunk, then perhaps the image state should be in the runtime chunk as well.

What happens to the old state in redux on dispatch of action resulting in new state

In Redux once we dispatch an action we get a new state with the updated values . What happens to the previous old state ?
The old state is discarded. If you want to save it, you need to incorporate it as part of your state. One way to do that is explained here: Implementing Undo History.
Another option is to use an "Event Sourcing" model. Where your primary state is merely an array of all actions that have transpired and you have a derivative state that reduces the array in the primary state into a "current app state." Here's an explanation of the idea for Elm: Elm and Event Sourcing
Redux state is nothing but a javascript object in your memory. There is only one version of the state, which is your latest one.
When you dispatch an action, the action handler (reducer) is a pure function which will convert your old state to new state. state should be immutable, which means the action handler does not change the old state, but get the copy of it, and then change it depends on your action type, then return it. It will looks like ("--->" means dispatch):
initial state ---> state 1 ---> state 2 ---> state 3 ....
You can install the redux plugin in chrome, and you will see the whole history of the state.
So basically, redux does not save any old state, if you wanna trace the history, you have to do it yourself by using Stack or using some other libs.
I actually implement the event tracing using data structure stack, when state changes, you push to stack, when you wanna go back to previous state, you just pop the state and dispatch a special action to change the state, this special dispatch should not trigger push, very rough idea though.

Redux / Flux Pattern for Fetching Data When Store Updates

I have what I believe is a very common scenario... I'm building a dashboard of components that will be driven by some datasource. At the top of the view would be a series of filters (e.g. a date range). When the date range is updated, the components on the screen would need to update their data based on the selected range. This would in turn force the individual components that are slave to that picker to need to fetch new data (async action/XHR) based on the newly selected range.
There can be many components on the screen and the user may wish to add/remove available displays, so it is not as simple as always refreshing the data for all components because they may or may not be present.
One way I thought to handle this was in the action dispatched when a new date range is selected was to figure out what components are on screen (derived from the Store) and dispatch async actions to fetch the data for those components. This seems like a lot of work will go into the DATE_CHANGED action.
Another alternative might be to detect date range changes in store.subscribe() callbacks from each of the components. This seems to decouple the logic to fetch the data from the action that caused this to happen. However, I thought it was bad practice (or even an error) to dispatch while dispatching. Sure I can wrap it in a setTimeout, but that feels wrong too.
Third thing that came to mind was just doing fetch calls directly in the component's store.subscribe() and dispatching when those return, but I thought this breaks the connect model.
This seems like a common pattern to fetch based on state changes, but I don't know where its best to put those. Any good documentation / examples on the above problem?
Don't use store.subscribe for this. When DATE_CHANGED reaches the reducer it's meant for, simply change the application state (I'm assuming the date range is part of the store somehow). So you have something like state.rangeStart and state.rangeEnd.
You didn't mention what view rendering library you're using, so I can only describe how this is typically done with React:
The components know wether they are currently mounted (visible) or not, so redux doesn't need to be concerned with that. What you need is a way to detect that state.rangeStart or state.rangeEnd changed.
In React there is a lifecycle hook for that (componentWillReceiveProps or getDerivedStateFromProps in the newest release). In this handler you dispatch async redux actions that fetch the data the component needs. Your view library will probably have something similar.
The components display some kind of "empty" or "loading" state while you're waiting for the new data typically. So a good practice is to invalidate/clear data from the store in the reducer that handles the DATE_CHANGED action. For example, if state.listOfThings (an array) entirely depends on the date range, you would set it to an empty array as soon as the date changes: return { ...state, listOfThings: [] }. This causes the components to display that data is being fetched again.
When all the async redux actions went through the REQUEST -> SUCCESS/FAILURE cycle and have populated the store with the data, connected components will automatically render it. This is kind of its own chapter, look into redux async actions if you need more information.
The tricky part are interdependencies between the components and the application they're rendering. If two different dashboard components for example want to fetch and render state.listOfThings for the current date range, you don't want to fetch this data twice. So there needs to be a way to detected that 1) the data range has changed but also 2) a request to fetch listOfThings is already on its way. This is usually done with boolean flags in the state: state.isFetchingListOfThings. The async actions fetching this data cause the reducer to set this flag to true. Your components need to be aware of this and dispatch actions conditionally: if (props.rangeStart !== nextProps.rangeStart && !nextProps.isFetchingListOfThings) { props.fetchListOfThings(); }.

Which pattern to store the selected item of a list in Redux

Let's imagine I want to be able to select a task in the Todo with React-Redux.
Where should I store this state ?
First solution: Add a isActive: true attribut to the task
Second solution: Create a new reducer just to handle the id of the selected item.
I dislike both solutions: the first one feels like I'm storing something unrelated to the task in it, the second one feels overkilled to create a whole reducer only to store an id.
Is there any other option ? What's best ?
Thanks
I'd say it depends on your use case.
For a big app that has tons of UI state to persist, it makes a lot of sense to have a special reducer to mutate a slice of the store related to the UI.
It is valid to have a isActive: boolean property per task if you can have multiple tasks active at the same time. Even though it's not related to the task from the task data perspective, it actually is from an application perspective of the task. Your redux store main goal is to be your application source of truth rather than just mirroring your API data models.
You can also have a single isActive: id if you can only have a single task active/selected at the time.
You can also just use the component state. The limitation of this is that it won't persist and it won't be shared. For instance, if you want to have a save button, that button will have to be within the component that has the selected state.
There's nothing really wrong with either of the two options you've listed. But, if you're looking for other options, you can
1) Include the selected item in the todos reducer state, so your state object would look like this:
{
selected: id,
list: [{id, text, completed}, ...]
}
2) If you don't need the selected item anywhere else in your app, you can simply store it in your local state. There's nothing wrong with mixing both Redux for application state and local state for data contained solely within your component.

Initialize part of Redux store on demand

I'm migrating my Reflux based application to the Redux and came across one issue. I have many stores in the application (which is a good or bad thing about Reflux) and some of them get initialized only when a certain page trying to use the store. Basically, the store initialization happens then a component connected to the store is about to mount. When initialising the store I actually loading the data asynchronously.
To illustrate the current behavior:
Suppose I have 5 pages and 5 stores, where each page using one store. The data for initial store state loaded only when the user navigates to the respective page. So, on initial application load, I only load data for store1 and only when user navigating to the page2 I'll load data for store2.
Now, I replacing my Reflux stores with a single Redux store which is consist of 5 parts and I'm planning to implement reducers for each of the parts. Every page if going to be associated with a reducer (page1 -> reducer1, page2->reducer2 etc.). From my understanding of how Redux is supposed to work, each parts of the store will be initialized by a respective reducer and it all will happen at the store initialization time. In the real application, I have, 50 stores, and I assume it will results in 50 API calls immediately at the application initialization which is not good at all. Not all of that data is required for the initial page.
Therefore my question: Is there any way to load the initial store state on demand in Redux? Or how could it be approached?
I understand, that I can fire an action to load data into the store before navigating to the page, but in reality, pages connected to several store parts and it is not easy to figure out what actions I need to call (although it is possible).
A similar question has been asked here but my question more about how to not load everything on initialisation.
Yes you can.
When you create your reducer, it is an good idea to give the state argument an default value so that when it is never undefined.
When you first initialize your store, you have the opportunity to pass down an initialState object. So you can do something like this:
let initialState;
if (yourDemand) { // load the intialState on 'yourDemand'
initialState = {
page1: intial state for page1Reducer
page2: intial state for page2Reducer
page3: intial state for page3Reducer
}
}
const store = createStore(
reducers,
initialState
);

Resources