I want to dispatch without a component. I made this code:
const handleClient = () => (dispatch) => {
try {
dispatch({
type: "SET_CLIENT",
user: {
id: 1,
name: "client",
},
});
} catch (err) {
console.log(err);
}
};
export default handleLogin;
But this code doesn't work. I import this file and use that in onSubmit event. I use Redux-Thunk. @Edit Look at this code from tutorial
export const fetchContacts = () => (dispatch) => {
fetch("https://myapi.local/contacts)
.then(res => res.json())
.then(json => dispatch(contactsFetched(json.results)));
};
I done something similar and it works so I don't understand that in this example it doesn't work. I tryed other method
import actions from "./actions";
import store from "../store";
const handleClient = () => {
try{
store.dispatch(actions.setClient({id: 1, name: 'Hello'}));
} catch(err){
console.log(err);
}
}
export default handleClient;
but it doesn't work too.
https://redux.js.org/api/store#dispatchaction
You need to have access to your instance of the redux store, which you created somewhere in your codebase via createStore()
. Then it's just store.dispatch(handleclient())
.
Please keep in mind that this is usually a rare requirement and potentially a code smell. Why is your thunk not triggered from within a React component?
You should never use store.dispatch
, so your first example is incorrect. Your second example is better, but the only place where you can use useDispatch
is inside a function component or a custom hook, you cannot use it inside a callback like handleLogin
.
Try to use useDispatch
at the beginning of your React component and then pass the dispatch function as an argument to handleLogin
.