Reputation: 838
I have followed this tutorial and I think I have done everything as required however I still have this warning:
Unhandled promise rejection: Error: Actions must be plain objects. Instead, the actual type was: 'Promise'. You may need to add middleware to your store setup to handle dispatching other values, such as 'redux-thunk' to handle dispatching functions. See https://redux.js.org/tutorials/fundamentals/part-4-store#middleware and https://redux.js.org/tutorials/fundamentals/part-6-async-logic#using-the-redux-thunk-middleware for examples.
My code:
store
this is my index.js
file:import { createStore, applyMiddleware } from "redux";
import thunkMiddleware from "redux-thunk";
import { composeWithDevTools } from "redux-devtools-extension";
import rootReducer from "../reducers/index";
const composedEnhancer = composeWithDevTools(applyMiddleware(thunkMiddleware));
const store = createStore(rootReducer, composedEnhancer);
export default store;
Inside my App.js
file:
...
import store from "./redux/store/index";
...
return (
<Provider store={store}>
<NavigationContainer>
<MainNavigator />
</NavigationContainer>
</Provider>
);
Inside my MainNavigator
file:
import { connect } from "react-redux";
import { bindActionCreators } from "redux";
import {someAsyncFunctionFromRedux} from "../../redux/actions/index";
...
const MainComponent = (props) => {
...
useEffect(() => {
async function f() {
await props.someAsyncFunctionFromRedux();
}
f();
}, []);
Inside my actions/index.js
export async function someAsyncFunction() {
return async (dispatch) => {
await firebase
.firestore()
.collection("Users")
.get()
.then( (snapshot) => {
let users = [];
snapshot.docs.map((doc) => {
const data = doc.data();
const id = doc.id;
users.push({id, ...data})
})
dispatch({ type: USERS_STATE_CHANGE, users });
});
};
}
Upvotes: 2
Views: 935
Reputation: 4879
I'm not exactly sure what the issue is, since the code you have provided is not consistent: in MainNavigator
you are importing a someAsyncFunctionFromRedux
but your example code only has a someAsyncFunction
. If it is the same function and just the example is wrong then the problem could be that you are returning an async function from an async function. Try this one (with some code improvements):
export async function someAsyncFunction(dispatch) {
const snapshot = await firebase
.firestore()
.collection("Users")
.get();
const users = snapshot
.docs
.map(({ id, data }) => ({ id, ...data() }));
dispatch({ type: USERS_STATE_CHANGE, users });
}
Upvotes: 2
Reputation: 47
The better way for using async functions with state management you have to use Redux-Thunk middleware and it is best practice I think.
see blow link for documentation:
Upvotes: 1