Here is what I have in my searchSlice:
export const search = param => (dispatch, getState) => {
dispatch(searchParamUpdated(param))
const items = getState().items.entities
dispatch(itemsMatchesByNameUpdated(items.filter(item => item.name.indexOf(param) > -1)))
dispatch(itemsMatchesByBrandUpdated(items.filter(item => item.brand.indexOf(param) > -1)))
}
Here is How I am using it in my component:
<input onChange={event => dispatch(search(event.target.value))}/>
I get error whenever I type in the input field. Here is my log:
redux-logger.js:1 Uncaught Error: Actions must be plain objects. Use custom middleware for async actions.
at Object.performAction (<anonymous>:1:34471)
at y (<anonymous>:1:36743)
at e (<anonymous>:1:40562)
at Object.dispatch (redux-logger.js:1)
at dispatch (<anonymous>:1:28545)
at onChange (Search.js:15)
at HTMLUnknownElement.callCallback (react-dom.development.js:188)
at Object.invokeGuardedCallbackDev (react-dom.development.js:237)
at invokeGuardedCallback (react-dom.development.js:292)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:306)
at executeDispatch (react-dom.development.js:389)
at executeDispatchesInOrder (react-dom.development.js:414)
at executeDispatchesAndRelease (react-dom.development.js:3278)
at executeDispatchesAndReleaseTopLevel (react-dom.development.js:3287)
at Array.forEach (<anonymous>)
at forEachAccumulated (react-dom.development.js:3257)
at runEventsInBatch (react-dom.development.js:3304)
at runExtractedPluginEventsInBatch (react-dom.development.js:3514)
at handleTopLevel (react-dom.development.js:3558)
at batchedEventUpdates$1 (react-dom.development.js:21871)
at batchedEventUpdates (react-dom.development.js:795)
at dispatchEventForLegacyPluginEventSystem (react-dom.development.js:3568)
at attemptToDispatchEvent (react-dom.development.js:4267)
at dispatchEvent (react-dom.development.js:4189)
at unstable_runWithPriority (scheduler.development.js:653)
at runWithPriority$1 (react-dom.development.js:11039)
at discreteUpdates$1 (react-dom.development.js:21887)
at discreteUpdates (react-dom.development.js:806)
at dispatchDiscreteEvent (react-dom.development.js:4168)
I have bootstrapped the application using create-react-app with redux template.
While adding redux-logger, I forgot to use getDefaultMiddleware().
export default configureStore({
reducer: {
search: searchReducer,
},
middleware: [...getDefaultMiddleware(), logger]
});
This caused the issue as store was no longer configured to use thunk middleware.
Related
I have deployed the following cloud function:
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.getAllUsers = functions.https.onRequest((req: any, res: any) => {
return admin.listUsers().then((userRecords: any) => {
userRecords.users.forEach((user: any) => console.log(user.toJSON()));
res.end('Retrieved all users successfully.');
}).catch((error: any) => console.log('Request failed: ', error));
})
But whenever I try to run it, I get the following error:
TypeError: admin.listUsers is not a function
at exports.getAllUsers.functions.https.onRequest (/srv/functions/lib/index.js:102:11)
at cloudFunction (/srv/functions/node_modules/firebase-functions/lib/providers/https.js:57:9)
at process.nextTick (/srv/node_modules/#google-cloud/functions-framework/build/src/invoker.js:243:17)
at process._tickCallback (internal/process/next_tick.js:61:11)
How do I resolve it? And how do I add a parameter to paginate my data, i.e. to get 100 users at a time or something? I am expecting to call the endpoint as follows: curl http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers. How would it look like with a parameter i.e. 'http://localhost:5000/sweltering-fire-5301/us-central1/getAllUsers?limit=5&page=2'
If you imported the admin SDK like this:
const admin = require("firebase-admin")
Then listUsers is available to you like this:
admin.auth().listUsers()
You might want to check out the documentation and API reference, as they have everything you need to make this happen.
I have moved own project to angular 6, #angular-redux/store 9 from 5 version. All was fine, but way for registrate epics in middleware not worked. I remove all epics from middleware except logger and startup was fine with all actions executed. Then i try add one epic and get error like
TypeError: action$.pipe is not a function
at SecurityUserEpics.loadSecurityUser (security-user.epic.ts:31)
at combineEpics.js:19
Then i try to solve this and search many examples and docs about, but cant find solution. After deciding to ask question here and while prepare code for question the solution was found. Soo, i post here that solution in hope that this will save time for someone.
epic:
loadSecurityUser = (action$) => {
debugger;
// here i have object of type : {getState: ƒ, dispatch: ƒ} and thats was pain from older version. pipe helps!
return action$.pipe(
ofType(SecurityUserActions.LoadSecurityUsers),
switchMap(q => this._dataSrv.getUserInfo()
.pipe(map(data => {
localStorage.setItem('isNeedRelogin', '0');
return this._securityUserActions.loadSecurityUserComplete(data);
}))));
}
And final config store:
const epicMiddleware = createEpicMiddleware();
const middleware = [epicMiddleware];
middleware.push(createLogger());
ngRedux.configureStore(combinedReducer, INITIAL_STATE, middleware, storeEnhancers);
const rootEpic = combineEpics(this._securityUserEpics.loadSecurityUser);
// this is new way of middleware registration
epicMiddleware.run(rootEpic);
Use provideStore instead configureStore, for example -
export const combinedEpics = combineEpics(
pingEpic,
fetchUserEpic
);
//replace ngRedux.configureStore with:
const epicMiddleware = createEpicMiddleware();
const store = createStore(
combinedReducer,
INITIAL_STATE,
applyMiddleware(createLogger(), epicMiddleware),
);
ngRedux.provideStore(store);
epicMiddleware.run(combinedEpics);
more information about epics - https://redux-observable.js.org/docs/basics/Epics.html
I am trying to dispatch an action in a saga function in this way:
yield put(addToCart(item));
When trying to execute it, it gives the error __webpack_require__.i(...) is not a function.
"addToCart" is an action creator which I imported:
export const addToCart = product => ({
type: types.ADD_TO_CART,
payload: { product },
});
This action never fires.
The item (or product) is an object, like :
{
'id' : 5,
'thing' : 'stuff'
}
(+ other properties).
I can dispatch other actions, but this one doesn't work for some reason.
I had imported the action creator wrongly:
import addToCart from './actionCreators'
It should be:
import { addToCart } from './actionCreators'
But what kind of error is "__webpack_require__.i(...) is not a function" ? The error messages are worthless, they give you no clue at what the error is about.
In a typical React/Redux codebase you have action creator functions like:
Actions.js:
export const addFoo = foo => ({ foo, type: 'ADD_FOO' });
Then you use connect to create a version of that function which dispatches the action, and make it available to a component:
Component.js:
import { addFoo } from 'Actions';
const mapPropsToDispatch = { addFoo };
const SomeComponent = connect(mapStateToProps, mapPropsToDispatch)(
({ addFoo }) =>
<button onClick={() => addFoo(5)}>Add Five</button>;
)
I was thinking, rather than mapping each action creator to its dispatched version inside the connect of every component that uses them, wouldn't it be simpler and cleaner if you could just "pre-connect" all of your action creators ahead of time:
Store.js:
import { createStore } from 'redux'
const store = createStore(reducer, initialState);
export const preConnect = func => (...args) => store.dispatch(func(...args));
Actions.js (2.0):
import { preConnect } from 'Store';
export const addFoo = preConnect(foo => ({ foo, type: 'ADD_FOO' }));
Component.js (2.0):
import { addFoo } from 'Actions';
const SomeComponent = () =>
<button onClick={() => addFoo(5)}>A Button</button>;
Am I missing any obvious reason why doing this would be a bad idea?
You make a reference to the dispatch() function in your code here:
export const preConnect = func => (...args) => store.dispatch(func(...args));
But in the world of React-Redux there is no direct reference to the dispatch() function inside of our components. So what's going on?
When we pass our action creator into the connect() function, the connect() function does a special operation on the functions inside the actions object.
export default connect(mapStateToProps, { selectSong })(SongList);
The connect() function essentially wraps the action into a new JavaScript function. When we call the new JavaScript function, the connect() function is going to automatically call our action creator, take the action that gets returned and automatically call the dispatch() function for us.
So by passing the action creator into the connect() function, whenever we call the action creator that gets added to our props object, the function is going to automatically take the action that gets returned and throw it into dispatch function for us.
All this is happening behind the scenes and you don't really have to think about it when using the connect() function.
So thats how redux works, there is a lot of wiring up and its one of the chief complaints I believe people have around this library, so I do understand your sentiment of wanting to pre-configure some of its setup and in this case, in my opinion, the toughest part of the Redux setup which is wiring up the action creators and reducers.
The problem with pre-configuring I am thinking is that the developer still needs to know how to write these functions and then manually hook them together as opposed to how its done in other state management libraries and if that is taken away by some type of pre-configuration process, Redux becomes more magical and harder to troubleshoot I think. Again the action creators and reducers are the biggest challenge in putting together a Redux architecture and so mastering and knowing how to troubleshoot that area almost requires manual setup to do so.
I'm trying to build a React + Redux app, and I'm using Redux Thunk.
One of my action creators looks like this:
import api from '../api';
export const FETCH_BOOKS = 'FETCH_BOOKS';
export default () => dispatch =>
api
.books()
.perPage(-1)
.then(books =>
dispatch(books => ({
type: FETCH_BOOKS,
books,
}))
)
.catch(error =>
dispatch(e => ({
type: 'ERROR',
error: e,
}))
);
But when I run yarn run build:production I get the error(s):
ERROR in ./scripts/ll-app/actions/fetch-books.js
/Users/joneslloyd/resources/assets/scripts/ll-app/actions/fetch-books.js
9:11 warning 'books' is defined but never used no-unused-vars
11:9 error Expected an assignment or function call and instead saw an expression no-unused-expressions
11:9 error 'books' is already declared in the upper scope no-shadow
17:12 warning 'error' is defined but never used no-unused-vars
19:9 error Expected an assignment or function call and instead saw an expression no-unused-expressions
19:9 error 'error' is already declared in the upper scope
However, I want to pass the books array (returned from the async api call) to the dispatch (anonymous function passed to dispatch) to then include said books array in the action, which the reducer will receive.
Am I doing something wrong here?
Even when I rename the inner reference to books it doesn't help.
It's possible I'm overlooking something in ES6 here.. But I basically want to take the books array returned from the api call (as a parameter of the then method), and then pass it into the dispatch function inside of that, as a parameter of the anonymous function I'm passing in.
Any help with this would be excellent. Thanks!
I'm not sure if this is the source of the problem, but why do you need the inner ref to books at all? Your error msg/linter is complaining about that.
...
api
.books()
.perPage(-1)
.then(books =>
dispatch({
type: FETCH_BOOKS,
books,
})
).catch(error => dispatch({type: ERROR, error}))
why won't the above do what you want?
no function in the dispatch necessary here.
dispatch needs a plain action. A function in dispatch is giving you the error.
When you see function in dispatch in the docs, those functions are function calls that are just returning the action.
export someActionCreator = () => ({type: ACTION, payload})
dispatch(someActionCreator());
Your functions are just statements and are not returning the action to the dispatch. which would be more akin to something like
export someActionCreator = () => ({type: ACTION, payload})
dispatch(someActionCreator);
see the difference?
Hope this helps!