Pass data from FormulateForm to a mapped action using Vuex - vue.js

I'm currently using Vue Formulate to pass data, using #submit="login" on a FormulateForm, to a login(data) function.
Everything's working nicely as long as I keep the logic inside the component and I can send the data to my server using axios.
Thing is, I would like to put this login function in my Vuex store, as an action, but when I refer the #submit="login" from FormulateForm to the ...mapActions(["login"]) function, there is no data passed inside.
I logged data in the login(data) action, and I get this:
Response from console.log(data) in the vuex module
I could bind values from my inputs into the store and get them from there, but I'd prefer to keep this simple and use #submit.
Is it at all possible to do so?
Overview of the actual code that is working:
methods: {
login(data) {
axios
.post("http://localhost:3000/api/auth/login", data, {
withCredentials: true
})
.then(res => {
if (res.status === 200) {
this.setUserRole(res.data.isAdmin);
this.$router.push("/");
}
})
.catch(err => {
if (err.response.status === 404) {
// TODO: gestion d'erreur
} else if (err.response.status === 401) {
// TODO: gestion d'erreur
}
});
}
)
<FormulateForm #submit="login">
Overview of what I want, that is not working:
methods: {
...mapActions(["login"])
)
<FormulateForm #submit="login">
Inside Vuex module user.js:
const actions = {
login: data => {
console.log(data);
axios
.post("http://localhost:3000/api/auth/login", data, { withCredentials: true })
.then(res => {
if (res.status === 200) {
this.setUserRole(res.data.isAdmin);
this.$router.push("/");
}
})
.catch(err => {
if (err.response.status === 404) {
// TODO: gestion d'erreur
} else if (err.response.status === 401) {
// TODO: gestion d'erreur
}
});
}
};
As stated, the console.log(data)does not return my FormulateForm values as it does currently.

You did not dispatch the action login.
Do this
<FormulateForm #submit="handleLogin">
methods: {
...mapActions(["login"]), // here, you have mapped `this.login()` to this.$store.dispatch('login')
handleLogin(data) {
this.login(data); // pass data as a parameter
}
)
Then your vuex user.js store should be changed to
const actions = {
login: ({commit, state}, data) => { // it takes two arguments here
console.log(data);
}
};
For more on actions, please check the Vuex documentation
Do these things and it should work.

Related

React Hook does not set on first API call

So I am sure I am messing something up, but I am not super skilled at API.
So I am trying to make an API call to check if the user exists, if user exists then move about business, if not then do other stuff.
So my first call gets the data, and the user DOES exist, the hook is setting to true, however in my log it fails and the next API is ran. However if I do it a 2nd time, it is true...
What am I doing wrong.
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
console.log(checkUser);
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
};
I think the problem here is that setCheckUser(true) is an async operation, so there is no guarantee that the checkUser variable will turn to true right away.
Maybe you can solve this by using a useEffect block like this
//somewhere on the top of your file, below your useState statements
useEffect(()=> {
if (!checkUser) {
console.log('No User Found');
//Do Stuff//
}
}, [checkUser])
const handleSubmit = async () => {
const data = await axios
.get(`URL`, {
})
.then((resp) => {
if (resp.data.user.name) {
setCheckUser(true);
console.log(resp.data.user.name);
}
return data;
})
.catch((err) => {
// Handle Error Here
console.error(err);
});
};

React redux - passing parameters to url - error - Actions must be plain objects

I want to attach params to react redux fetch action and I searched for many days the redux docs, but even after trying out a few things i am getting this error:
[Unhandled promise rejection: Error: Actions must be plain objects. Use custom middleware for async actions.]
https://codesandbox.io/s/fast-framework-ct2fc?fontsize=14&hidenavigation=1&theme=dark
The original action looks like this:
export function fetchArticleDetails() {
return apiAction({
url: "http://myurl/appApi/2.0.0/getData/1", //1 should be an optional value
onSuccess: setArticleDetails,
onFailure: () => console.log("Error occured loading articles"),
label: FETCH_ARTICLE_DETAILS
});
}
function setArticleDetails(data) {
console.log(data);
return dispatch({
type: SET_ARTICLE_DETAILS,
payload: data
});
}
i tried to set the param directly
export function fetchArticleDetails(id)
...
url: `http://myurl/appApi/2.0.0/getData/${id}`,
or some variations to put the params in the payload directly
function setArticleDetails(data) {
console.log(data);
return dispatch({
type: SET_ARTICLE_DETAILS,
payload: data,
userid: id
});
}
All this results in the same error. Anyone have an idea where to place the dynamic data to solve it?
Another idea could be to set the params in my reducer maybe?
Update store/index.js
import { createStore, applyMiddleware } from "redux";
import rootReducer from "../reducers";
import apiMiddleware from "../middleware/api";
const store = createStore(rootReducer, applyMiddleware(apiMiddleware));
window.store = store;
export default store;
update: middleware/api.js
import axios from "axios";
import { API } from "../actions/types";
import { accessDenied, apiError, apiStart, apiEnd } from "../actions/api";
const apiMiddleware = ({ dispatch }) => next => action => {
next(action);
if (action.type !== API) return;
const {
url,
method,
data,
accessToken,
onSuccess,
onFailure,
label,
headers
} = action.payload;
const dataOrParams = ["GET", "DELETE"].includes(method) ? "params" : "data";
// axios default configs
axios.defaults.baseURL = process.env.REACT_APP_BASE_URL || "";
axios.defaults.headers.common["Content-Type"] = "application/json";
axios.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
if (label) {
dispatch(apiStart(label));
}
axios
.request({
url,
method,
headers,
[dataOrParams]: data
})
.then(({ data }) => {
dispatch(onSuccess(data));
})
.catch(error => {
dispatch(apiError(error));
dispatch(onFailure(error));
if (error.response && error.response.status === 403) {
dispatch(accessDenied(window.location.pathname));
}
})
.finally(() => {
if (label) {
dispatch(apiEnd(label));
}
});
};
export default apiMiddleware;
function apiAction()
function apiAction({
url = "",
method = "GET",
data = null,
accessToken = null,
onSuccess = () => {},
onFailure = () => {},
label = "",
headersOverride = null
}) {
return {
type: API,
payload: {
url,
method,
data,
accessToken,
onSuccess,
onFailure,
label,
headersOverride
}
};
}
There are a couple of issues with the code. apiMiddleware should only pass the action to the next middleware in the chain if it's not of type API.
const apiMiddleware = ({ dispatch }) => (next) => (action) => {
if (action.type !== API) {
return next(action)
}
// do stuff
}
Since the apiMiddleware dispatches what onFailure returns, the function has to return an object. In fetchArticleDetails, you're passing () => console.log("Error occured loading articles") causing apiMiddleware to dispatch undefined.
export function fetchArticleDetails(id) {
return apiAction({
url: `https://jsonplaceholder.typicode.com/todos/${id}`,
onSuccess: setArticleDetails,
onFailure: (error) => ({
type: FETCH_ARTICLE_ERROR,
payload: error
}),
label: FETCH_ARTICLE_DETAILS
})
}
CodeSandbox
I would strongly recommend using React Query to simplify data fetching, managing, and syncing server state.

React native axios call throws 403 but postman correctly outputs the data

I'm working on a RN app, which has redux in it. Now I can login with the help of jwt but when Im trying the to get the data from my other component its giving me 403 error. Please find below the relevant code.
Here is my reducer:
const initState = {
isLoadingCollegeDashList : false,
collegeDashList:{},
collegeDashListFail:false
}
const collegeReducer = ( state = initState, action) => {
switch(action.type){
case 'IS_LOADING_COLLEGE_DASH_LIST' :
return{
...state,
isLoadingCollegeDashList: true,
collegeDashList : false
}
case 'COLLEGE_DASH_LIST' :
return {
...state,
isLoadingCollegeDashList : false,
collegeDashList : true,
userData : action.userData
}
case 'COLLEGE_DASH_LIST_FAIL' :
return{
...state,
isLoadingCollegeDashList:false,
collegeDashList: false,
collegeDashListFail: action.error
}
default :
return state
}
}
and here's my action that's making get request
export const populateCollege = (token) => {
const headers = {
'api-secret' : ...secret...,
'authorization':...authToken...,
'Content-Type': 'application/json',
}
return dispatch => {
dispatch(isLoadingCollegeDashList(true));
return axios.get( '...api/api/...', {
},{
headers:headers,
})
.then((response) => {
if(response.status < 300){
dispatch(isLoadingCollegeDashList(false))
dispatch(collegeDashList(response))
console.log(response);
}
else{
response.json().then((responseJSON) => {
console.log("responseJSON",responseJSON);
dispatch(isLoadingCollegeDashList(false))
dispatch(collegeDashListFail(responseJSON.message))
})
}
})
.catch((error) => {
console.log("error",error);
dispatch(isLoadingCollegeDashList(false))
dispatch(collegeDashListFail(error))
})
}
}
export const isLoadingCollegeDashList = (bool) => {
return{
type:'IS_LOADING_COLLEGE_DASH_LIST',
isLoadingCollegeDashList:bool
}
}
export const collegeDashList = (userData) => {
return{
type:'COLLEGE_DASH_LIST',
userData
}
}
export const collegeDashListFail = (error) => {
return{
type:'COLLEGE_DASH_LIST_FAIL',
error
}
}
here's action that im calling if you want to check it
const mapDispatchToProps = dispatch => ({
populateCollege : (token) => dispatch(actions.populateCollege({token}))
});
PS I've for now stored token in the state of one hence passing the token from this dispatch itself.
Let me know if you need any clarification / more information then do let me know. Thanks in advance
Make sure you have the authorisation schema before your token. The schema can be like Basic, Bearer or any other value based on your authorisation details. (eg. Authorization: Bearer TOKEN).
Also, try to reuse your auth headers while creating the axios instance so you won't need to inject them on every call.

Vue returning from a promise

I am trying to return some value from this dispatch
this.$store.dispatch('setValue', this.Value)
.then(response => {
console.log(response)
});
In my vuex action I have
.catch(error => {
if (error.response.status === 412) {
return "some message"
}
});
How can I pass the error back to the .vue file where the vuex dispatch is made?
I think the correct way of doing this is to have a status property in your store.
Your status object would consist out of error, success, loading.
So if your action throw exception you can handle it like this:
catch (error) {
commit("error", `Some Message`);
}
Your error mutation would look like this:
error(state, payload) {
state.status.success = false;
state.status.loading = false;
state.status.error = payload || false;
}
Your template would just listen on the store.state.status
<div v-if="store.state.status.error">{{store.state.status.error}}</div>
I might be wrong but in my personal opinion I feel it is wrong to use actions to return stuff. Your using the store so might as well leverage it best you can.
Other extra benefits is, you can indicate to your .vue file if api is loading or when something is successful.
What I ended up doing was pretty simple. I chained the catch to my dispatch:
this.$store.dispatch('setValue', this.Value)
.then(response => {
console.log(response)
})
.catch(error => {
if (error.response.status === 412) {
return "some message"
}
});
Then I returned the Axios call from the action:
return axios({
method: 'post',
url: `/mypath,
data: mydata,
json: true,
})
This means I could deal with the returned data/errors locally where I wanted to trigger an action.
Store:
.catch(error => {
if (error.response.status === 412) {
throw error
}
});
Vue element with async method:
try{
let response = await this.$store.dispatch('setValue', this.Value)
} catch(error) {
console.log(error)
});

Catch Axios exception in Vuex store and throw it to Vue.js method

How to catch axios exceptions in vuex store and throw it to vue.js method ? My goal is to get this exception to be able to reset computed values bound to input using this.$forceUpdate().
In my method, I have this:
methods: {
mymet: _.debounce(
function(table, id, key, event) {
const value = event.target.value;
this.$store.dispatch('UPDATE_TRANSACTIONS_ITEM', { table, id, key, value }).then(response => {
event.target.classList.remove("is-invalid")
event.target.classList.add("is-valid")
}, error => {
console.error("Got nothing from server. Prompt user to check internet connection and try again")
this.$forceUpdate();
})
}, 500
)
}
In my vuex store, I have this:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {
[data.key]: data.value
}
axios.put(`/api/companies/${data.id}`, { company }).then( function ( response ) {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
}).catch(function (error) {
throw error
})
}
}
const mutations = {
SET_TRANSACTIONS_ITEM_UPDATE (state, { profile }) {
state.company_data[profile.key] = profile.value
},
}
You need to make the actual action function asynchronous.
If you have the ability to use async functions, you can just await the axios call, and let the error bubble up (no need to throw anything in the action itself):
const actions = {
async UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
let company = {[data.key]: data.value};
await axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data })
});
}
}
Otherwise, you'll need to return a Promise and catch the error and pass it to the reject handler:
const actions = {
UPDATE_TRANSACTIONS_ITEM ({ commit }, data) {
return new Promise((resolve, reject) => {
let company = {[data.key]: data.value};
axios.put(`/api/companies/${data.id}`, { company }).then(() => {
commit('SET_TRANSACTIONS_ITEM_UPDATE', { profile: data });
resolve();
}, (error) => reject(error));
});
}
}