I'm beginner with React/Redux.
I want to authenticate a User and display a notification on my app when error occurs.
This is my login function:
const [loading, setLoading] = useState(false);
const dispatch = useDispatch();
const handleSignIn = (values: SignInOpts, setSubmitting: any) => {
setLoading(true);
dispatch(authenticationActions.signInAndFetchUser(values))
.then(res => {
console.log("SignIn Success");
setLoading(false);
})
.catch(err => {
console.log("SignIn Failure");
setLoading(false);
showErrorNotification(
"Error notification"
);
});
};
My action:
export const signInAndFetchUser = (credentials: SignInOpts) => {
return (dispatch, getState) => {
return dispatch(signIn(credentials)).then(res => {
const token = getState().authentication.token;
return dispatch(getMe(token));
});
};
};
The error I have :
How can I perform this ?
Most of your work should happen in the thunk (the action). dispatch does not return a promise. So you have to handle your promise inside your thunk and dispatch the corresponding action, it will then be send to the reducer. The new state will reflects the changes.
Here is a thunk which should give you an idea of how it works :
export const signInAndFetchUser = (credentials: SignInOpts) => {
return (dispatch, getState) => {
dispatch(action.startLoading);
signIn(credentials)
.then((res) => {
// do something with res : maybe recover token, and store it to the store ?
// if the token is in the store already why do you need to signIn ?
dispatch(action.signedInSuccess(res.token));
getMe(res.token)
.then((user) => {
dispatch(action.getMeSucceded(user));
})
.catch((err) => dispatch(action.getMeFailed(err)));
})
.catch((err) => dispatch(action.signInFailed(err)));
};
};
Or using async/await :
export const signInAndFetchUser = (credentials: SignInOpts) => {
return async (dispatch, getState) => {
dispatch(action.startLoading);
try {
const res = await signIn(credentials);
dispatch(action.signedInSuccess(res.token));
try {
const user = await getMe(res.token);
dispatch(action.getMeSucceded(user));
} catch (err) {
dispatch(action.getMeFailed(err));
}
} catch {
dispatch(action.signInFailed(err));
}
};
};
Generally for thunks, dispatch(myThunk()) will return whatever the thunk returns and can be a Promise, as also the case in your signInAndFetchUser method.
The problem is that the normal useDispatch hook typings do not know which middlewares you are using and thus have no overload for that behaviour.
That is why the Redux TypeScript Quickstart Tutorial recommends you define your own, correctly-typed hooks:
// Use throughout your app instead of plain `useDispatch` and `useSelector`
export const useAppDispatch = () => useDispatch<AppDispatch>()
export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector
If you are using the official Redux Toolkit (especially with TypeScript, you definitely should as it cuts out almost all type annotations), you can just get
export type AppDispatch = typeof store.dispatch
If you are using old-style vanilla Redux, just use ThunkDispatch as AppDispatch.
dispatch do not return promise so you cannot pipe .then. From Action the pipeline flows to reducer, and reducer returns the state back to your component via useSelector for functional component and connect for class based component. So you need to hook those to receive login success object via state
On the outside it seems not an issue, but when I open the DevTools and then go to network tab. It shows that there are 500 requests made. So how can I refactor the code so this will not happens?
useEffect(() => {
const fetchData = async () => {
try {
const response = await axios.get(
"https://raw.githubusercontent.com/XiteTV/frontend-coding-exercise/main/data/dataset.json"
);
dispatch(getData(response.data));
console.log('input');
} catch (err) {
console.log(err);
}
};
fetchData();
}, [dispatch]);
with redux first create a function which will push your request data into redux state like that outside your react component
export const getMyData = () => {
return async (dispatch) => {
const response = await axios.get(
"https://raw.githubusercontent.com/frontend-coding-exercise/main/data/dataset.json"
);
dispatch(getData(response.data));
}
}
create a function that will extract data from redux. state is redux current state, ownProps is your component props, like <Component customProp={1}/>
const mapStateToProps = (state: any, ownProps: any) => {
return {
...ownProps,
myProps: state.user
};
};
In your connect Function pass the function which will store your data in redux state
export default connect(mapStateToProps, { getMyData })(MyReactComponent);
that way you'll be able to access your data via your component props and also access your getMyData function and also the redux state you mapped to props
props.getMyData();
I'm really struggling with Redux. I have one component where my input field is, and user should type in a word so I use that as a query in fetch request (which is in actionCreators file). I set that word to state so I want to pass that term to action and use it in fetch URL.
Component:
<button className='search-btn'
onClick={() =>
this.props.getResults(this.state.searchTerm)}>
const mapDispatchToProps = dispatch => {
return {
getResults: (term) => dispatch(getData(term))
}
}
actionCreators.js:
export const getData = (term) => {
return (dispatch) => {
fetch(`...url...${term}`)
.then(response => response.json())
.then(data => {
console.log(data)
dispatch({type: 'GET_DATA', results: data})
})
}
}
In reducer, I set data to be action.results.
All I get is TypeError: dispatch is not a function
mapDispatchToProps is a second param to connect, the first is mapStateToProps:
default connect (null, mapDispatchToProps)(Search);
Official docs.
This is the correct usage of connect.
export default connect(mapStateToProps, mapDispatchToProps)(Search);
Unhandled Rejection (Error): Actions must be plain objects. Use custom middleware for async actions.
I wanted to add comments with every posts. So when fetch posts are run I want to call fetch comment API for all post.
export function bindComments(postId) {
return API.fetchComments(postId).then(comments => {
return {
type: BIND_COMMENTS,
comments,
postId
}
})
}
You have to dispatch after the async request ends.
This would work:
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
For future seekers who might have dropped simple details like me, in my case I just have forgotten to call my action function with parentheses.
actions.js:
export function addNewComponent() {
return {
type: ADD_NEW_COMPONENT,
};
}
myComponent.js:
import React, { useEffect } from 'react';
import { addNewComponent } from '../../redux/actions';
useEffect(() => {
dispatch(refreshAllComponents); // <= Here was what I've missed.
}, []);
I've forgotten to dispatch the action function with (). So doing this solved my issue.
useEffect(() => {
dispatch(refreshAllComponents());
}, []);
Again this might have nothing to do with OP's problem, but I hope I helps people with the same problem as mine.
The error is simply asking you to insert a Middleware in between which would help to handle async operations.
You could do that by :
npm i redux-thunk
Inside index.js
import thunk from "redux-thunk"
import { createStore, applyMiddleware } from 'redux';
...createStore(rootReducers, applyMiddleware(thunk));
Now, async operations will work inside your functions.
You can't use fetch in actions without middleware. Actions must be plain objects. You can use a middleware like redux-thunk or redux-saga to do fetch and then dispatch another action.
Here is an example of async action using redux-thunk middleware.
export function checkUserLoggedIn (authCode) {
let url = `${loginUrl}validate?auth_code=${authCode}`;
return dispatch => {
return fetch(url,{
method: 'GET',
headers: {
"Content-Type": "application/json"
}
}
)
.then((resp) => {
let json = resp.json();
if (resp.status >= 200 && resp.status < 300) {
return json;
} else {
return json.then(Promise.reject.bind(Promise));
}
})
.then(
json => {
if (json.result && (json.result.status === 'error')) {
dispatch(errorOccurred(json.result));
dispatch(logOut());
}
else{
dispatch(verified(json.result));
}
}
)
.catch((error) => {
dispatch(warningOccurred(error, url));
})
}
}
Change:
export const <youractionName> = async (dispatch) => {}
to,
export const <youractionName> = () => async (dispatch) => {}
This fixed my issue. Missed a '() =>'
Make use of Arrow functions it improves the readability of code.
No need to return anything in API.fetchComments, Api call is asynchronous when the request is completed then will get the response, there you have to just dispatch type and data.
Below code does the same job by making use of Arrow functions.
export const bindComments = postId => {
return dispatch => {
API.fetchComments(postId).then(comments => {
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
};
I had same issue as I had missed adding composeEnhancers. Once this is setup then you can take a look into action creators. You get this error when this is not setup as well.
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(
rootReducer,
composeEnhancers(applyMiddleware(thunk))
);
You might also have forgotten to getDefaultMiddleware() in the middlewares' array, as I did. No further installations required:
export const store = configureStore({
reducer: GlobalReducer,
middleware: (getDefaultMiddleware) => [
...getDefaultMiddleware(),
mainMiddleware,
],
});
Without middleware, redux supports only synchronous data flow. If you need to make ajax request and dispatch the result of this request, then you need to use middlewares that handles the async operations like, redux-promise, redux-thunk or redux-saga. Or you could write your own middleware:
export default ({ dispatch }) =>
(next) =>
(action) => {
// check if there is payload in action. if not send it to the next middleware
if (!action.payload || !action.payload.then) {
return next.action;
}
// if we are here means we have action.payload. now check if it is promise
// wait for the promise to be resolved
action.payload.then(function (response) {
// overwrite the action
const newAction = { ...action, payload: response };
dispatch(newAction);
});
};
I have solved my issue changing :
export const = async (dispatch) => {}
to,
export const = () => async (dispatch) => {}
Use redux-thunk, setup with redux & create action like this
export const actionName = (data) => dispatch => {
dispatch({
type:"ACTION_TYPE",
payload:"my payload"
})
}
Action Definition
const selectSlice = () => {
return {
type: 'SELECT_SLICE'
}
};
Action Dispatch
store.dispatch({
type:'SELECT_SLICE'
});
Make sure the object structure of action defined is same as action dispatched. In my case, while dispatching action, type was not assigned to property type.
If you are working with redux-observable check that your action returns an observable. I had the issue because I used map and not a mergemap
// error
export const myEpic = (action$: any) =>
action$.pipe(
ofType('...'),
map((x => x.payload),
map((x) => callAPi(x)),
)
// success
export const myEpic = (action$: any) =>
action$.pipe(
ofType('...'),
map((x => x.payload),
mergeMap((x) => callAPi(x)),
)
Just here to share my case.
I had a setLoading action, while also having
const [loading, setLoading] = useState(false)
above which I didn't delete. So it was basically not dispatching the setLoading from redux but the one from useState. Deleting/renaming this solves the problem.
if things were working with this code and this is a new iteration, check to make sure you have your variables in the correct order for the function (this was my mistake)
i.e.
code that got this error
export const fetchProjects = newPage => (getState, dispatch) => NOPE
export const fetchProjects = newPage => (dispatch, getState) => OK YEAH
In my case, I just wanted to sent some values to the server without saving them to redux store, so I was not using a type, nor dispatching anything at the end. But I was calling the action with dispatch. So all I had to do, was to remove the dispatch, because it wasn't really an action. It was just a function.
For me, the solution was to add redux-thunk as a middleware, so inside my store configuration file, I passed redux-thunk as middleware.
inside the console:
import reducerData from './store-reducer';
import {applyMiddleware, compose, createStore} from 'redux';
import ReduxThunk from 'redux-thunk';
const middlewares = [ReduxThunk];
const store = createStore(
reducerData,
compose(applyMiddleware(...middlewares)),
);
export default store;
Arrow function syntax
export const bindComments = (postId) => dispatch => {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
})
})}
This error occurs mainly if you are dispatching an action and your action is not returning an object. For example here is an increment function which I use it to increment number value when increment button is clicked.
const increment = () => type: INCREMENT and here is my dispatch function onClick={() => dispatch(increment)} because of ommiting parenthesis
() inside dispatch function now in your terminal there would be the same error appears. The reason dispatch function expects an object not a function name...
This error occurs when you make an asynchronous api call in your action creator you need to convert your action creator from synchornous action creator to asynchronous action and this conversion can be possible if we use the middleware so let me explain you in detailRedux without middleware
Two types of action creators
Sync Action Creator VS Async Action Creator. you need to change sync action to async action in order to get rid of this error and this can be done with middleware
Redux with middleware
enter image description here
So now solution is:
Dispatch after the async request would befinished.
export function bindComments(postId) {
return function(dispatch) {
return API.fetchComments(postId).then(comments => {
// dispatch
dispatch({
type: BIND_COMMENTS,
comments,
postId
});
});
};
}
Whenever you wish to perform async operation with redux shore you must use middleware ex. redux-thunk
Error:
action.js
export const login = () => async (dispatch, getState) => {}
sore.js
import reducerData from './store-reducer';
import {createStore} from 'redux';
const middlewares = [ReduxThunk];
const store = createStore(
reducerData,
);
export default store;
Solution:
import reducerData from './store-reducer';
import {applyMiddleware, compose, createStore} from 'redux';
import ReduxThunk from 'redux-thunk';
const middlewares = [ReduxThunk];
const store = createStore(
reducerData,
compose(applyMiddleware(...middlewares)),
);
export default store;
A reason for this error I had that caught me off guard—
Dispatch was failing in a test even though the action creator was synchronous. Turned out I was mocking the action creator and this was the error it gave when it wasn't returning because of that.