How do I use qs.stringify in Vue 3? - vuejs3

I'm trying to use qs stringify to encode URL parameters in a Vue Axios call. In my main.js I have the following:
import { createApp } from 'vue'
import Search from './Search.vue'
import axios from 'axios'
import VueAxios from 'vue-axios'
import qs from 'qs'
const search = createApp(Search);
search.use(VueAxios, axios, qs);
search.mount('#v_search_app');
Then in Search.vue, I have the following:
let params = {
"q": this.q,
"page": this.page,
"per_page": this.perPage,
"filters": {
"page": {
"source_table_enum": this.selectedSources
"topic_id": this.selectedTopics
}
}
}
let queryString = this.qs.stringify(params);
This results in the following error:
Uncaught TypeError: Cannot read properties of undefined (reading 'stringify')
What am I doing wrong?

In your Search.vue, you should do this:
import qs from 'qs'
let queryString = qs.stringify(params)
You have to import the library into the component you want to use it.

Related

how to access Vuex store from Axios config file?

I'm using Vue 3 composition and Vuex
this is axios config file
http.js
import axios from "axios";
import useStore from "#/stores/index.js";
const store = useStore()
const http = axios.create({
//from env
baseURL: "https://challenge.spexa.dev/"
})
http.interceptors.request.use(function (config) {
console.log("store" + store) // return undefined
const token = store.getters['token']
if (token) {
config.headers.Authorization = 'Bearer ' + token;
}
return config;
});
export default http
the problem is that store works fine inside component But not in axios config module and I cant access it (!!!?) .
and this is store
store/index.js
import Vuex from "vuex";
import http from "../services/http";
export default new Vuex.Store({
state: {
access_token: null,
refresh_token: null,
},
getters: {
token(state) {
return state.access_token
}
},
});
and this is main.js
import { createApp } from 'vue'
import store from './stores/index';
import App from './App.vue'
createApp(App).use(store).mount('#app')
so ,what's the problem ?
so ,what's the problem ?
well, hard to tell without seeing what useStore from "#/stores/index.js" is doing.
store works fine inside component But not in axios config module
Is not a lot to go one and you may need to define what "not" working means. Is sotre undefined or is the value not staying reactive?
Maybe you meant to do this 🤷‍♂️:
import { store } from "#/stores/index.js";
instead of"
import useStore from "#/stores/index.js";
const store = useStore()

VueJs ,Vue.use(VueI18n) or app.use(VueI18n) TypeError: Cannot read properties of undefined (reading 'use')

I use VueI18n but i have an error:
TypeError: Cannot read properties of undefined (reading 'use')
How con i solve this error?
Thnx?
import VueI18n from 'vue-i18n';
import { languages } from './i18n/index.js';
app.use(VueI18n);//here i have error
let locale = 'it';
const messages = Object.assign(languages);
export const i18n = new VueI18n({
locale: locale,
fallbackLocale: 'it',
messages,
i18n
});
you have to create the application before using it :
main :
import App from './App.vue';
import VueI18n from 'vue-i18n';
const app = createApp(App);
app.use(VueI18n);
Where and what is your 'app'?
You can try this:
import { createApp } from 'vue'
const app = createApp({})
or
import { createApp } from 'vue'
import App from './App.vue'
const app = createApp(App)
then
app.use(VueI18n)

How to add `redux-logger` on middlewares?

I want to add redux-logger on the middlewares chain. Below is my code:
import {createStore, combineReducers, applyMiddleware, compose} from 'redux';
import reducers from './index';
import createLogger from 'redux-logger';
import thunk from 'redux-thunk';
const logger = createLogger ({
log: 'info',
});
// create the global store
const store = compose (applyMiddleware (thunk, logger)) (createStore) (
reducers
);
export default store;
I will get below error with above code:
applyMiddleware.js:39 Uncaught TypeError: middleware is not a function
at applyMiddleware.js:39
at Array.map (<anonymous>)
at applyMiddleware.js:38
It works fine if I change the apply middleware to this line:
applyMiddleware (thunk, createLogger)
but I need to create the logger with some specific parameters. How can I add the created logger into middleware chain?
import { applyMiddleware, compose, createStore } from 'redux';
import reducers from './index';
import thunk from 'redux-thunk';
import { logger } from 'redux-logger';
const composeEnhancers = typeof window === 'object' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__({}) : compose;
const middlewareList = [thunk, logger]
const enhancer = composeEnhancers(
applyMiddleware(...middlewareList)
);
const store = createStore(reducers, enhancer);
export default store;
It should working fine if you change your store into this:
const store = createStore(reducers, compose(applyMiddleware(thunk, logger)));
If that doesn't work, take a look into this issue. It should do the same as above code I think.
https://github.com/gaearon/redux-thunk/issues/35
Fixed this issue by changing the import to import {createLogger} from 'redux-logger';.

Angular2 HTTP using observables subscribe showing data undefined

I don't know what I'm doing wrong but somehow i'm not able to read data, though the data is coming from server in response and even the data is getting showed inside service extractData method when I'm putting the console but in component inside subscribe function it is giving me undefined. Help me what I'm doing wrong, what I'm assuming is that this is the problem of async but, I have no idea how correct it.
Any help will be appreciable.
Thanx in advance
Component.ts
import { Component, Input, OnInit } from '#angular/core';
import {AdminService} from './admin.service';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
import { Observable } from 'rxjs/Observable';
import {Response } from '#angular/http';
#Component({
moduleId:module.id,
selector: 'admin',
templateUrl: 'admin.component.html',
styleUrls:['admin.component.css'],
providers:[AdminService]
})
export class AdminComponent implements OnInit{
#Input() public allocatedAssetsList: logistics[];
mode = 'Observable';
public errorMsg = '';
constructor(private adminService: AdminService) {
}
ngOnInit(){
this.listByEmpId("123");
}
listByEmpId(empId:string){
this.adminService.getAllocatedAssets(empId).subscribe(
res => this.allocatedAssetsList = res,
error => this.errorMessage = <any>error);
}
}
Service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import { Hero } from './hero';
import { Observable } from 'rxjs/Observable';
import { Headers, RequestOptions } from '#angular/http';
import {logistics} from '../shared/model/logistics';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/debounceTime';
import 'rxjs/add/operator/distinctUntilChanged';
import 'rxjs/add/operator/switchMap';
import 'rxjs/add/operator/toPromise';
#Injectable()
export class AdminService {
constructor (private http: Http) {}
private listAssetsURL = '/api/logistics/list/'; // URL to web API
private extractData(res: Response) {
let body = res.json();
return body || { };
}
private handleError (error: any) {
// In a real world app, we might use a remote logging infrastructure
// We'd also dig deeper into the error to get a better message
let errMsg = (error.message) ? error.message :
error.status ? `${error.status} - ${error.statusText}` : 'Server error';
console.error(errMsg); // log to console instead
return Observable.throw(errMsg);
}
getAllocatedAssets (empId: string): Observable<logistics[]> {
this.listAssetsURL+= empId;
//let body = JSON.stringify({ empId });
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
return this.http.get(this.listAssetsURL)
.map(this.extractData)
.catch(this.handleError);
}
}
listByEmpId(empId:string){
this.adminService.getAllocatedAssets(empId).subscribe(
res => {
this.allocatedAssetsList = res;
console.log(this.allocatedAssetsList);
},
error => this.errorMessage = <any>error);
}
This is probably because you are trying to access your allocatedAssetsLists before the data is actually returned from the service.
If you are accessing it in your template you can use a simple ngIf to make sure you only try to display it once the data is available.
If this is not it, we need more information on your problem to help.

want to do dispatch.then(...)

I use redux, react-redux, react-router, and react-router-redux, and redux-thunk.
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import { browserHistory } from 'react-router'
import { routerMiddleware } from 'react-router-redux'
import thunkMiddleware from 'redux-thunk'
...
const reduxRouterMiddleware = routerMiddleware( browserHistory )
const store = createStore(
mainReducer,
applyMiddleware(reduxRouterMiddleware, thunkMiddleware)
)
I was hoping as a result to be able to do thenable dispatch
dispatch(...).then()
but I get the message that then is not a function of dispatch.
How can I accomplish this?
the answer: it depends on what is returned by dispatch; if a promise is returned, then it will be thenable.

Resources