I want to dispatch outside component. I want to use option 2 from this link [https://daveceddia.com/access-redux-store-outside-react/][1]. My code look like this
const loginUser = async (data) => {
return axios.get(url + "/sanctum/csrf-cookie").then(() => {
axios.post(url + '/api/login', data)
.then(res => {
return res.data
})
.catch((err) => {
console.log(err);
})
})
}
export const handleLogin = (data) => async (dispatch) => {
console.log('test');
try {
const user = await loginUser(data);
dispatch(actions.setUser(user));
} catch (err) {
console.log(err);
}
}
And into my component
const test = (e) => {
e.preventDefault;
handleLogin({email: 'test@test.pl', password: 'password'})
}
return (
<div className="container">
<h2>Login</h2>
<form onSubmit={handleSubmit(test)}>
//...
It doesn't finish code and it may contain mistakes but currently the most important for me is why this code doesn't work and if sometimes is wrong why doesn't show any error. I think that problem is in sync(dispatch). In this example I add console.log for test and it wasn't display. Without that function display console.log. Redux thunk is added to the store too
const store = createStore(allReducers, composeWithDevTools(applyMiddleware(thunk)))
import store and use like this :
store.dispatch(actions.setUser(user));
and you can get state out of component with :
store.getState().items
you did not dispatch your actions in your component and in your action js . you can call an action in component by props and dispatch and I could not see the props so I use useDispatch and call handleLogin action there.
use this in action.js file:
const user = await loginUser(data)(dispatch);
instead :
const user = await loginUser(data);
then in component:
import {useDispatch} from "react-redux";
const dispatch = useDispatch();
const test = (e) => {
e.preventDefault;
dispatch(handleLogin({email: 'test@test.pl', password: 'password'}))
}