StoreModule.forRoot() - how to return object without additional key - ngrx

I am wondering how can I return object of the same type as reducer function:
function storeReducer(
state = INITIAL_APPLICATION_STATE,
action: Actions
): ApplicationState {
switch (action.type) {
case LOAD_USER_THREADS_ACTION:
return handleLoadUserThreadsAction(state, action);
default:
return state;
}
}
I expect object of type ApplicationState, but with that approach:
StoreModule.forRoot({storeReducer})
I am getting object with key:
storeReducer:{ // object of type Application State}
I am expecting to get object (without additional storeReducer key):
{//object of type Application State}
Tried also StoreModule.forRoot(storeReducer) but then I am getting empty objects and it is not working.

The forRoot method on StoreModule expects and ActionReducerMap, not the result of your reducer.
I typically set mine up in a seperate file like this:
export interface IAppState {
aPieceOfState: IAPieceOfState;
}
export const reducers: ActionReducerMap<IAppState> = {
aPieceOfState: aPieceOfStateReducer
};
Then import this to app.module.ts and use it like:
StoreModule.forRoot(reducers)

Or you can put an assertion StoreModule.forRoot({storeReducer} as ActionReducerMap<IAppState>)

Related

React Redux Search Reducer

Currently I have the below reducer switch statement. All it does is toggles the state of Sidebar, so first it shows then hides then shows. It's easy.
switch(action.type) {
case 'SIDEBAR_DISPLAY_TOGGLE':
return {
...state,
Sidebar : {
...state.Sidebar,
Display : !state.Sidebar.Display
}
}
default:
return state;
}
Now I have a input field like here
that people can type to search account. I am trying to set up Redux so when user types, it gets saved to the Redux global state and I can pull it from another component. I have this reducer code set up for it but I don't know how can I pull what user types into this reducer from that component?
function reducer(state = initialState, action) {
switch(action.type) {
case 'ACCOUNT_SEARCH':
return {
...state,
AccountNumberSearch : {
...state.AccountNumberSearch,
AccountNumber : ''
}
}
default:
return state;
}
}
}
An action is just an object with a string value named type. Any other properties on this object will also be passed, so you use this to pass the typed text.
If you're using a function to create your actions, something along the lines of:
export function accountNumberSearch(accountNumber) {
return { type: 'ACCOUNT_SEARCH', accountNumber };
}
Then in your reducer, you'll be able to assign the value in the state to action.accountNumber.
AccountNumberSearch : {
...state.AccountNumberSearch,
AccountNumber : action.accountNumber,
}
Then you can map your state to props as you normally would (as you did for the sidebar toggle).
Also, as an aside, you should look into modularising your reducers with combineReducers - Docs
This would be much easier than the way you're doing it.
EDIT: Handling the changes
First of all, you'd want to wire up your input field for the search box to an onChange listener. If you do this like onChange={this.onSearchChange} you can get the value from event in the function:
onSearchChange = event => {
this.props.AccountNumberSearch(event.target.value);
}
Then in mapDispatchToProps you'd send your action + the passed value to dispatch:
const mapDispatchToProps = dispatch => {
return {
AccountNumberSearch: AccountNumber => dispatch(importedActions.AccountNumberSearch(AccountNumber)),
}
}
Then, in the component you want to RECEIVE this value, you'd map the redux state to props, like:
const mapStateToProps = state => {
return {
AccountNumber: state.AccountNumberSearch.AccountNumber,
}
}
Then you can access that value in your render function by calling this.props.AccountNumber.
If you need to do something when this value changes, you can always listen on componentDidUpdate, and compare the value with the old one - if it changed, call whatever function that you need to do.

Can passing an action object an empty object upon initialization affect application state?

I have this function here that has an action given an empty object:
export default reducer(state = initialState, action = {}) {
switch(action.type) {
return {
...state, blahblah
}
}
}
Is it possible this could create some type of bug or better framed, why could this be a bad practice? With my understanding of how reducers work, I don't see the point in giving initializing the action with an empty object.
I dont see the point either. Your action creators will(be required to) always return an object with a type/payload so seems unnecessary to set a default

Redux Reducer - State

So I'm just getting started with redux.I am trying to fetch some gifs from an API.
My goal is to return an array of img urls instead of the whole response data.However if I try to iterate and return each image my state remains null.If I use return action.payload.data.data; which returns the whole response then this works but I only want to get the img urls.
Here is the corresponding reducer.
import _ from 'lodash';
export default function(state = null,action) {
switch(action.type) {
case 'FETCH_GIF':
_.forOwn(action.payload.data.data, function(value, key) {
var img = value.images.downsized.url;
return img;
});
// return action.payload.data.data;
default:
return state;
}
}
state = null looks a bit wrong, it should normally default to some kind of initialState object. Then in your case block it's not really clear what the _.forOwn is supposed to return. Are you trying to mutate action.data.data? If so, maybe check if that is actually happening. Also your state returned by the reducer should be an object, I don't think redux works when you return an array.

Flow Type + Redux: Type for action that won't conflict with actions for other reducers

I have a reducer for storing preferences. It has two action types. One for loading in all preferences from database and another for updating a single preference. I have a working standalone example but it breaks once used inside of my app.
The issue is that my preferences reducer only handles two types of actions, while my app has multiple reducers that fire other actions. A solution to get the code running is to add a third general type for actions not related to this reducer. That however creates Property not found in 'object type'. errors when I try to access properties of the action.
Working flow example
// #flow
const LOAD_PREFS_SUCCESS = 'LOAD_PREFS_SUCCESS';
const UPDATE_PREF = 'UPDATE_PREF';
type aType = {
+type: string
};
export type actionType = {
+type: typeof LOAD_PREFS_SUCCESS,
prefs: Array<{_id: string, value: any}>
} | {
+type: typeof UPDATE_PREF,
id: string,
value: any
};
export default (state: {} = {}, action: actionType) => {
if (action.type === LOAD_PREFS_SUCCESS) {
action.prefs.forEach(p => {
console.log(p);
});
}
switch (action.type) {
case LOAD_PREFS_SUCCESS: {
const newState = {};
action.prefs.forEach(p => {
newState[p._id] = p.value;
});
return newState;
}
case UPDATE_PREF: {
return { ...state, [action.id]: action.value };
}
default:
return state;
}
};
This is valid flow but when the app actually runs, I get an error when an action with type INIT_APP or something runs. The error says action must be one of: and then it lists the two types I have in actionType as the expected and an actual of { type: string }.
I can get the app running by adding a third type to actionType like this:
export type actionType = {
+type: typeof LOAD_PREFS_SUCCESS,
prefs: Array<{_id: string, value: any}>
} | {
+type: typeof UPDATE_PREF,
id: string,
value: any
} | {
+type: string
};
Even though the app now runs without error, it does not pass flow type check. Throwing errors of Property not found in object type. Here is an example on flow.org
Since every reducer ends up seeing every action, you'll want the type of this reducer function to include all the possible actions in your app. I usually define a single variant actionType with everything available in the app and use that in every reducer.
The reason why your last code example doesn't work is because the third, anonymous action type {type: string} is too vague. Before this, Flow could look at the two options in the action, and see that it would know which one was which based on the case statements. But with the third action type, an action like {type: "LOAD_PREFS_SUCCESS"} would match the third case in the type. So testing action.type === LOAD_PREFS_SUCCESS is no longer enough to prove that the action will have a prefs key.
So there are two ways to fix this:
If you change your action type to be more specific and include all the specific action types, your reducer should go back to type-checking.
Otherwise, add a dummy case, like | {type: "NOT-REAL"} so that Flow forces your reducer to have a default case for actions it doesn't understand.

React-redux project - chained dependent async calls not working with redux-promise middleware?

I'm new to using redux, and I'm trying to set up redux-promise as middleware. I have this case I can't seem to get to work (things work for me when I'm just trying to do one async call without chaining)
Say I have two API calls:
1) getItem(someId) -> {attr1: something, attr2: something, tagIds: [...]}
2) getTags() -> [{someTagObject1}, {someTagObject2}]
I need to call the first one, and get an item, then get all the tags, and then return an object that contains both the item and the tags relating to that item.
Right now, my action creator is like this:
export function fetchTagsForItem(id = null, params = new Map()) {
return {
type: FETCH_ITEM_INFO,
payload: getItem(...) // some axios call
.then(item => getTags() // gets all tags
.then(tags => toItemDetails(tags.data, item.data)))
}
}
I have a console.log in toItemDetails, and I can see that when the calls are completed, we eventually get into toItemDetails and result in the right information. However, it looks like we're getting to the reducer before the calls are completed, and I'm just getting an undefined payload from the reducer (and it doesn't try again). The reducer is just trying to return action.payload for this case.
I know the chained calls aren't great, but I'd at least like to see it working. Is this something that can be done with just redux-promise? If not, any examples of how to get this functioning would be greatly appreciated!
I filled in your missing code with placeholder functions and it worked for me - my payload ended up containing a promise which resolved to the return value of toItemDetails. So maybe it's something in the code you haven't included here.
function getItem(id) {
return Promise.resolve({
attr1: 'hello',
data: 'data inside item',
tagIds: [1, 3, 5]
});
}
function getTags(tagIds) {
return Promise.resolve({ data: 'abc' });
}
function toItemDetails(tagData, itemData) {
return { itemDetails: { tagData, itemData } };
}
function fetchTagsForItem(id = null) {
let itemFromAxios;
return {
type: 'FETCH_ITEM_INFO',
payload: getItem(id)
.then(item => {
itemFromAxios = item;
return getTags(item.tagIds);
})
.then(tags => toItemDetails(tags.data, itemFromAxios.data))
};
}
const action = fetchTagsForItem(1);
action.payload.then(result => {
console.log(`result: ${JSON.stringify(result)}`);
});
Output:
result: {"itemDetails":{"tagData":"abc","itemData":"data inside item"}}
In order to access item in the second step, you'll need to store it in a variable that is declared in the function scope of fetchTagsForItem, because the two .thens are essentially siblings: both can access the enclosing scope, but the second call to .then won't have access to vars declared in the first one.
Separation of concerns
The code that creates the action you send to Redux is also making multiple Axios calls and massaging the returned data. This makes it more complicated to read and understand, and will make it harder to do things like handle errors in your Axios calls. I suggest splitting things up. One option:
Put any code that calls Axios in its own function
Set payload to the return value of that function.
Move that function, and all other funcs that call Axios, into a separate file (or set of files). That file becomes your API client.
This would look something like:
// apiclient.js
const BASE_URL = 'https://yourapiserver.com/';
const makeUrl = (relativeUrl) => BASE_URL + relativeUrl;
function getItemById(id) {
return axios.get(makeUrl(GET_ITEM_URL) + id);
}
function fetchTagsForItemWithId(id) {
...
}
// Other client calls and helper funcs here
export default {
fetchTagsForItemWithId
};
Your actions file:
// items-actions.js
import ApiClient from './api-client';
function fetchItemTags(id) {
const itemInfoPromise = ApiClient.fetchTagsForItemWithId(id);
return {
type: 'FETCH_ITEM_INFO',
payload: itemInfoPromise
};
}

Resources