I am wondering how to use async/await actions in Vuex. The docs provide this syntax as an example:
actions: {
async actionA ({ commit }) {
commit('gotData', await getData())
},
async actionB ({ dispatch, commit }) {
await dispatch('actionA') // wait for `actionA` to finish
commit('gotOtherData', await getOtherData())
}
}
Following this example, I have:
import Vue from 'vue';
import Vuex from 'vuex';
import * as firebase from 'firebase';
Vue.use(Vuex);
export const store = new Vuex.Store({
state: {
// other state vars here
resource: null
},
mutations: {
// saveValues
setResource(state, payload) {
state.resource = payload;
}
},
actions: {
async getResource({ commit, dispatch }) {
var resource
console.log('resource1: ' + resource)
Vue.http.get('https://mysite/api/getResource')
.then((response) => {
console.log('get resource')
var data = response.body;
resource = data.access_resource;
console.log('resource2: '+ resource)
commit('setResource', resource);
var foo = store.getters.resource;
console.log('resource3: ' + foo);
}, (error) => {
console.log(error);
});
},
async getSomeApi({ commit, dispatch }) {
console.log('getting api');
await dispatch('getResource');
var resource = store.getters.resource;
console.log('resource4: ' + resource);
Vue.http.get('https://somesite/api/someapi?resource=' + resource)
.then((response) => {
console.log("got something from somesite")
var data = response.body;
// do something with data -> payload
dispatch('saveValues', payload);
}, (error) => {
console.log(error);
});
}
},
getters: {
resource(state) {
return state.resource;
}
}
});
However, even following the syntax example found in the docs, when I run this code, the async/await seem to be completely ignored. When I look at the logs, I see, in the following order:
getting api
resource1: undefined
resource4: null
get resource
resource2: <expected-value>
resource3: <expected-value>
I expect the console.log statements to print out in numerical order. I would appreciate if someone could clarify what I am doing wrong.
You're not awaiting the Vue.http.get() promise in the getResource() method, so await dispatch('getResource') will resolve before the HTTP request has resolved.
Trimmed down:
async getResource() {
let response
try {
response = await Vue.http.get('https://mysite/api/getResource')
} catch (ex) {
// Handle error
return
}
// Handle success
const data = response.body
}
Related
So I have a project using the latest Next js 13, React 18, Urql 3, and using typescript
Currently, I have issues when trying to query the urql from the getstaticprops function. My urql request needs a guest token, and I'm storing the token on session storage(other suggestions ?).
It has no issue when the query is running on the client, but I have it when querying inside the function.
My concern is related to the token reading, so the server cannot read the session storage value.
I'm asking what is the better and simplest way to make this work.
Does use cookies to store guest tokens will make this work?
Or the configuration that doesn't work?
This is my current config for urql.ts
import {
createClient,
ssrExchange,
dedupExchange,
cacheExchange,
fetchExchange,
} from "urql";
import { GRAPH_URL } from "#lib/constant/env";
import type { TypedDocumentNode } from "#urql/core";
const isServerSide = typeof window === "undefined";
const ssrCache = ssrExchange({
isClient: !isServerSide,
});
const client = createClient({
url: GRAPH_URL,
exchanges: [dedupExchange, cacheExchange, ssrCache, fetchExchange],
fetchOptions: () => {
const token = sessionStorage.getItem("accessToken");
return {
headers: {
authorization: token ? `Bearer ${token}` : "",
},
};
},
});
const query = async (
query: TypedDocumentNode<any, object>,
variables?: Record<string, string | string[] | unknown>
) => {
try {
const response = await client.query(query, variables as any).toPromise();
return response;
} catch (error) {
if (error instanceof Error) console.error(error.message);
}
};
const mutation = async (
mutation: TypedDocumentNode<any, object>,
variables?: Record<string, string | string[] | unknown>
) => {
try {
const response = await client
.mutation(mutation, variables as any)
.toPromise();
return response;
} catch (error) {
if (error instanceof Error) console.error(error.message);
}
};
export { client, query, mutation, ssrCache };
And this some of the code for the blog index page
export const getStaticProps = async () => {
await fetchArticlesSummary();
return {
props: {
urqlState: ssrCache.extractData(),
},
revalidate: 600,
};
};
export default withUrqlClient(() => ({
url: GRAPH_URL,
}))(BlogPage);
This is for the fetchArticlesSummary
export const fetchArticlesSummary = async () => {
try {
const {
data: { listArticles },
}: any = await query(getListArticle);
return listArticles.items;
} catch (error) {
return {
notFound: true,
};
}
};
I also doing a setup on _app.tsx
export default function App({ Component, pageProps }: AppProps) {
if (pageProps.urqlState) {
ssrCache.restoreData(pageProps.urqlState);
}
return (
<Provider value={client}>
<Component {...pageProps} />
</Provider>
);
}
Thank you
I have followed urql documentation about server-side configuration and many others but still don't have any solutions.
I have such kinds of reducers that use fetch API as its base ultimately:
export const fetchRelatedFamilies = () => {
return (dispatch, getState) => {
if (isEmpty(getState().relatedFamiliesById)) {
dispatch({ type: REQUEST_RELATED_FAMILIES_BY_ID })
new HttpRequestHelper('/api/related_families',
(responseJson) => {
dispatch({ type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: responseJson.relatedFamiliesById })
},
e => dispatch({ type: RECEIVE_RELATED_FAMILIES_BY_ID, error: e.message, updates: {} }),
).get()
}
}
}
Code for HttpRequestHelper is here: https://github.com/broadinstitute/seqr/blob/master/ui/shared/utils/httpRequestHelper.js
Here is how I am trying to test it (but its not working):
import configureStore from 'redux-mock-store'
import fetchMock from 'fetch-mock'
import thunk from 'redux-thunk'
import { cloneDeep } from 'lodash'
import { fetchRelatedFamilies, REQUEST_RELATED_FAMILIES_BY_ID, RECEIVE_RELATED_FAMILIES_BY_ID } from 'redux/rootReducer'
import { STATE1 } from '/shared/components/panel/fixtures.js'
describe('fetchRelatedFamilies', () => {
const middlewares = [thunk]
const testActionsDispatch = async (currstate, expectedActions) => {
const store = configureStore(middlewares)(currstate)
store.dispatch(fetchRelatedFamilies())
// need to mimick wait for async actions to be dispatched
//await new Promise((r) => setTimeout(r, 200));
expect(store.getActions()).toEqual(expectedActions)
}
afterEach(() => {
fetchMock.reset()
fetchMock.restore()
})
it('Dispatches correct actions when data - relatedFamiliesById - is absent in state', () => {
const relatedFamiliesById = cloneDeep(STATE1.relatedFamiliesById)
fetchMock
.getOnce('/api/related_families', { body: relatedFamiliesById, headers: { 'content-type': 'application/json' } })
STATE1.relatedFamiliesById = {}
const expectedActions = [
{ type: REQUEST_RELATED_FAMILIES_BY_ID },
{ type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: relatedFamiliesById }
]
testActionsDispatch(STATE1, expectedActions)
})
})
I don't see { type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: relatedFamiliesById } in the resulting store actions, so I tried to use the trick: await new Promise((r) => setTimeout(r, 200)); in hope that it's the issue with async fetch but what it causes is that test will pass no matter what expected actions are as if the code that is following await is completely being ignored. I can't use store.dispatch(fetchRelatedFamilies()).then(... probably because Promise is not returned, and I am getting then access of undefined error. I tried to use waitFor from the library: https://testing-library.com/docs/guide-disappearance/ but I am having really big troubles installing the library itself due to the nature of the project itself and its version, so I need to avoid it still somehow.
So, the only question that I have is how I can make the action dispatched inside the async reducer to appear, in this case - { type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: relatedFamiliesById }.
The problem with the current code is that although you are awaiting for 200ms in your testActionsDispatch helper method (so that the mocked promise is resolved), you are not awaiting in the test code for that promise of 200ms to resolve.
In order to do that you have to declare your test as async and await for the execution of the testActionsDispatch code:
const testActionsDispatch = async (currstate, expectedActions) => {
const store = configureStore(middlewares)(currstate)
store.dispatch(fetchRelatedFamilies())
// need to mimick wait for async actions to be dispatched
await new Promise((r) => setTimeout(r, 200));
expect(store.getActions()).toEqual(expectedActions)
}
// Note that the test is declared as async
it('Dispatches correct actions when data - relatedFamiliesById - is absent in state', async () => {
const relatedFamiliesById = cloneDeep(STATE1.relatedFamiliesById)
fetchMock
.getOnce('/api/related_families', { body: relatedFamiliesById, headers: { 'content-type': 'application/json' } })
STATE1.relatedFamiliesById = {}
const expectedActions = [
{ type: REQUEST_RELATED_FAMILIES_BY_ID },
{ type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: relatedFamiliesById }
]
// Await the execution of the helper code
await testActionsDispatch(STATE1, expectedActions)
})
Now that should work, but we are adding a delay of 200ms in every test that uses this testActionsDispatch helper. That can end up adding a lot of time when you launch your test and ultimately at a logical level is not really ensuring that the promise resolves.
A better approach is to return the promise in your reducer so we can wait for it to resolve directly in the test (I'm assuming the get method from HttpRequestHelper returns the promise created by fetch and returning it):
export const fetchRelatedFamilies = () => {
return (dispatch, getState) => {
if (isEmpty(getState().relatedFamiliesById)) {
dispatch({ type: REQUEST_RELATED_FAMILIES_BY_ID })
return new HttpRequestHelper('/api/related_families',
(responseJson) => {
dispatch({ type: RECEIVE_RELATED_FAMILIES_BY_ID, updates: responseJson.relatedFamiliesById })
},
e => dispatch({ type: RECEIVE_RELATED_FAMILIES_BY_ID, error: e.message, updates: {} }),
).get()
}
}
}
Then, in your helper you can simply await for this returned promise to resolve:
const testActionsDispatch = async (currstate, expectedActions) => {
const store = configureStore(middlewares)(currstate)
// Await for the promise instead of awaiting a random amount of time.
await store.dispatch(fetchRelatedFamilies())
expect(store.getActions()).toEqual(expectedActions)
}
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.
i'm trying to use this kind of structure.
I have my axios calls in a service file and then call them in vue files.
So i have this js file
const DashboardService = {
getStationList() {
let url = '/api/stations/list'
ApiService.get(url) //ApiService is an Axios wrapper
.then(response => {
console.log(response.data) //data are logged, function is called
response.data
})
}
}
export default DashboardService
Then in the Vue File i have this:
import DashboardService from '#/_services/admindashboard.service'
export default {
methods: {
getMarkers() {
let result = DashboardService.getStationList()
console.log(result) //undefined
}},
mounted() {
this.getMarkers()
}
}
I can't understand why result is undefined because che getStationList() function gets called... when the component is mounted the functions should have returned the response... how can i solve this situation?
getStationList is an async function, so you'll need to await it's result (or use then). For example:
async mounted() {
this.markers = await DashboardService.getStationList();
},
Also see this question for more details.
Next, you are missing a return in the implementation of getStationList.
const DashboardService = {
getStationList() {
const url = '/api/stations/list';
ApiService.get(url).then(response => {
return response.data;
});
},
};
or perhaps:
const DashboardService = {
async getStationList() {
const url = '/api/stations/list';
try {
const response = await ApiService.get(url);
return response.data;
} catch (error) {
console.error(error);
return [];
}
},
};
The result is undefined because getStationList is not returning anything.
You can consider turning your api call into an async function that returns the result.
const DashboardService = {
async getStationList() {
let url = '/api/stations/list';
return ApiService.get(url);
}
}
export default DashboardService
And in your component
methods: {
async getMarkers() {
let result = await DashboardService.getStationList();
console.log(result);
}
},
If you don't want to use the async await syntax. You can return a the promise from your service and utilize the result on your component, as so:
methods: {
getMarkers() {
DashboardService.getStationList().then(result => {
console.log(result);
});
}
},
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));
});
}
}