Variable in data section can't get API response value (response.data) - vue.js

I accessed API to upload image and return the image URL with Vue app. I want to set API response value to imgUrl1 in data section. I' sure getting correct response in console but imgUrl1 is still empty. Anybody idea ?? Thank you so much !
Vue
data () {return
{
imgUrl1:'',→empty
}
},
methods: {
uploadFile1: function () {
var img_file1 = this.$refs.img1.files[0]
var params = new FormData()
params.append('image', img_file1)
params.append('client_name', this.tableSelected)
axios.post("http://127.0.0.1:5000/", params
).then(function (response) {
console.log(response.data)→image url exists
this.imgUrl1 = response.data
}).catch(function (error) {
for(let key of Object.keys(error)) {
console.log(key);
console.log(error[key]);
}
});
}
console.log(response.data)
https://storage.googleapis.com/dashboard_chichat/img/クライアント名/xxxxxxxxnQSkX6Wudy.jpg

try using arrow functions in your then callback so the value of this is your Vue component.
methods: {
uploadFile() {
...
axios.post('', params)
.then((response) => {
this.imgUrl1 = response.data
})
}
}
the equivalent of it without arrow functions is:
methods: {
uploadFile() {
...
const _this = this;
axios.post('', params)
.then(function (response) {
_this.imgUrl1 = response.data
})
}
}

Related

Urql config with guest token for SSG on next js

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.

filter query param not working through axios get from my vue js application?

whenever a user types anything into the textfield, an axios get request to the url
http://sandbox4.wootz.io:8080/api/data/1/action/?filter={id}like'%TE%' is made and it is supposed to return back all the filtered results based on the search(what user has typed) as a response. But currently rather than returning the filtered results as a response it is giving out all results(non-filtered results).
NOTE: I have tested the above mentioned URL through postman by making a get request and it gave out the filtered results perfectly.Why is the same not happening through my application code?plz help
getAsyncDataAction: debounce(function(name) {
if (!name.length) {
this.dataAction = [];
return;
}
this.isFetching = true;
api
.getSearchData(this.sessionData.key,`/action/?filter={id}like'%${name}%'`)
.then(response => {
this.dataAction = [];
response.forEach(item => {
this.dataAction.push(item);
});
console.log('action results are'+JSON.stringify(this.dataAction)) //displays all the results(non-filtered)
})
.catch(error => {
this.dataAction = [];
throw error;
})
.finally(() => {
this.isFetching = false;
});
}, 500),
api.js
import axios from 'axios';
const props = {
base_url: '/api/store',
search_url: '/api/entity/search',
cors_url: 'http://localhost',
oper_url: '/api'
};
axios.defaults.headers.get['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.post['Access-Control-Allow-Origin'] = props.cors_url;
axios.defaults.headers.patch['Access-Control-Allow-Origin'] = props.cors_url;
async function getSearchData(key, path) {
try {
console.log('inside getSearchData path value is'+path)
console.log('inside getSearchData and url for axios get is '+props.base_url + '/data' + path)
let response = await axios({
method: 'get',
url: props.base_url + '/data' + path,
headers: {'session_id': key}
});
if (response.status == 200) {
console.log(response.status);
}
return response.data;
} catch (err) {
console.error(err);
}
}
The problem is that you're not encoding the query string correctly. In particular, your % signs need to become %25
To do this, I highly recommend using the params options in Axios.
For example
async function getSearchData(key, path, params) { // 👈 added "params"
// snip
let response = await axios({
method: 'get',
url: `${props.base_url}/data${path}`,
params, // 👈 use "params" here
headers: {'session_id': key}
});
and call your function with
const params = {}
// check for empty or blank "name"
if (name.trim().length > 0) {
params.filter = `{id}like'%${name}%'`
}
api
.getSearchData(this.sessionData.key, '/action/', params)
Alternatively, encode the query parameter manually
const filter = encodeURIComponent(`{id}like'%${name}%'`)
const path = `/action/?filter=${filter}`
Which should produce something like
/action/?filter=%7Bid%7Dlike'%25TE%25'

how to save specific data from json object in new state into react native

Here is my code
handleLogin = async()=> {
const { navigation } = this.props;
const errors = [];
Keyboard.dismiss();
this.setState({ loading: true });
if(this.state.email!=''){
if(this.state.password!=''){
fetch('http://192.168.1.10:8000/api/login',{
method:'post',
headers:{
'Content-Type':'application/json',
'Accept': 'application/json'
},
body:JSON.stringify({
"email":this.state.email,
"password":this.state.password
})
})
.then((response)=> response.json())
.then((res)=>{
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
if(this.state.store==='{"error":"Unauthorised"}'){
Alert.alert("Error", "These credentials do not match our records");
}
else {
Alert.alert("Success","You have succesfuly login",
[
{
text: 'Continue', onPress: () => {
Actions.NavigationCalling();
}
}
],
{ cancelable: false })
}
}).catch((error)=>{
console.error(error);
});
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert Password")
}
}
else{
this.setState({ errors, loading: false });
Alert.alert("Please insert email")
}
var store=JSON.stringify(res)
Im storing data in store variable that print output like this
{"success":{"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiIsImp0aSI6Ijk4YjYzNTY4NjNkNmYxNzBhYjdlYjVmNWRiN2MxNWU1NTUzNDc3OWUyZjM5Mjc5NWU4ODMzMjM3NDU1Y2Q3ODg1YzYzZTc0NDg2MmNjYzk2In0.eyJhdWQiOiIxIiwianRpIjoiOThiNjM1Njg2M2Q2ZjE3MGFiN2ViNWY1ZGI3YzE1ZTU1NTM0Nzc5ZTJmMzkyNzk1ZTg4MzMyMzc0NTVjZDc4ODVjNjNlNzQ0ODYyY2NjOTYiLCJpYXQiOjE1ODA5MzA2MzYsIm5iZiI6MTU4MDkzMDYzNiwiZXhwIjoxNjEyNTUzMDM2LCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.A1NZcxICOu8mudwrIrozG5FYiQxWyz1O8LcHFcaOvgXUlTkgUIuGuwxif74goMwCLkWrm3wIwZSKwMAxCAk35Ao9VZEsV3uOlelWtsjJY7u-o00baCUl3dZWJeBHLLfSODM719Oinrfepp5VGaGZ4r--rMqMnNljVEoUP8GuM0l_7rY-SA7dhXkj4a8TwogkZOzf1_0ZvgNYmM30Z_CU0umM72Iqcys-URnzb80HONI4_cVcYExqmU94UqhNsNJ9aMIDXR4WdMGzDBzhRat_E75u7Rbt67UKUbbwALv3J1qhGRb-kkE_DGR3DyAxlcNvMy21CR4b4obDE4e96GYb-7R7fLw0PiVtiyFTgLeL2Ldvw4YV8_v2TwF5zLgkh0VCqfjUTIbAir9ytjDBPDzXFy7G4mAR6qJYNPSHtgwzBcMuS2B4FWZruWg-0QbHiBFFQrDGISaf5jUTSCmiSbpd3eTKAhiifBE6eGNnzErlsG1WAn8L7zK233l1b7qDSoahIrK4PTllgsdEzFtI4sXpy_9mEbRmGmEjOTXZcUyvkFm6aajXrRwWGrhSMFIeFqRd2BNTnrh2Igwl9x7Dcj89VgXKGXyh-hP4ESwT5yHAynNhVfhaXAu1kdnkzhwzk5cDlKlYawvX02g83THN6UAElj2bttIutM-fZ1ViLIOA98k"}}
But i want to store just token in new state and pass to other screen
how can i get only token from json object and store into newstate and pass into new screen
Thanks in advance I'm new in the React native
You can access the token by doing res.success.token or you can map the json response to an object.
.then((res)=>{
var token = res.success.token // did you try doing this?
var store=JSON.stringify(res)
this.setState({ errors, loading: false });
....
And to pass the token to another screen you can use the screen props or use redux, however, i would set it in a static variable to be accessed globally by all the screens.
I am working on a react native app that does pretty much the same that you are trying to do, i created a class called ApiService that has the following function:
static async post(url: string, payload?: object, headers?: HeadersInit_): Promise<ApiResponse> {
return await fetch(url, {
method: "POST",
headers: headers,
body: JSON.stringify(payload),
}).then(r => r.json().then(o => {
var mapper = new ApiResponse();
mapper.success = o.success;
mapper.result = o.success ? JSON.stringify(o.result) : o.error;
return mapper;
})).then(response => {
if (response.success)
return response;
throw ApiError(response);
});
}
The ApiResponse class looks like this:
class ApiResponse {
public success: boolean;
public result: string;
}
To access the auth token globally, i am setting the token in a static variable in a class that can be accessed everywhere.
class AbstractService {
private static sessionToken: string;
public static setSessionToken(value: string): void {
AbstractService.sessionToken = value;
}
public static getSessionToken(value: string): string {
return AbstractService.sessionToken;
}
If you want to store the token to be reused, you can use react-native-secure-key-store

Vue JS - How to get function result in methods()

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);
});
}
},

IBM Worklight JSONStore | Remove Document from Collection and erase it from memory

I have been trying to erase all document from collection and memory before adding new one. I tried it by following methods
1.
WL.JSONStore.get("users").findAll().then(function (arrayResults){
var options={push:true};
if(arrayResults.length>0){
for(var i=1;i<=arrayResults.length;i++){
WL.JSONStore.get("users").remove(i,options);
}
}
});
2.
WL.JSONStore.get("users").findAll().then(function (arrayResults){
var options={};
if(arrayResults.length>0){
for(var i=1;i<=arrayResults.length;i++){
WL.JSONStore.get("users").erase(i,options);
}
}
});
But didn't get success. Its showing all documents by doing findAll
You can use the removeCollection API call to remove all docs in a collection, you will have to re-init the collection if you want to use it again.
Alternatively, try following this example:
function wlCommonInit () {
WL.JSONStore.init({
users: {
name: 'string'
}
})
.then(function () {
return WL.JSONStore.get('users').add([{name: 'hello'}, {name: 'world'}]);
})
.then(function () {
return WL.JSONStore.get('users').findAll();
})
.then(function (res){
alert('Before - Docs inside:' + JSON.stringify(res));
var ids = res.map(function(current){ return current._id })
var promises = [];
while (ids.length) {
promises.push(WL.JSONStore.get('users').remove(ids.pop()));
}
return WLJQ.when.apply(null, promises);
})
.then(function () {
return WL.JSONStore.get('users').findAll();
})
.then(function (res) {
alert('After - Docs inside:' + JSON.stringify(res));
})
.fail(function (err) {
alert('Failed:' + err.toString());
});
}