How to pass in Apps Metadata to a Class Method? - javascript

In refactoring my Bug Report code I moved a function into a new Class 'Logger', and call the static method as seen below:
$("#bugForm").submit((e) => {
e.preventDefault()
const input = document.getElementById('nameInput');
bugInfo = {
"name": `[${ticket.id}] Bug report`,
"story_type" : "Bug",
"description": `+ ${urlHelper.zendeskTicketUrl}` + " \n" + `+ ${input.value}`,
}
Logger.logInfo(bugInfo).then(collapse.collapse('toggle'))
})
});
however when I run the static method I receive the following error:
Uncaught (in promise) ReferenceError: metadata is not defined
Logger.js
class Logger {
constructor(settings) {
this.settings = settings;
}
static async logInfo(data = {}) {
console.log('Hello!')
const url = 'exampleUrl'
const response = fetch(url, {
method: 'POST',
headers: {
"Token": `${metadata.settings.token}`,
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
return response.json();
}
}
In an attempt to fix this, I placed the following line in my code:
const logger = new Logger(metadata.settings);
And received the following error:
Uncaught (in promise) ReferenceError: Cannot access 'Logger' before initialization
I originally only made the class to use its static method, does the need for metadata prevent me from doing this? Am I not using this correctly?

So the problem the way you're passing the metadata.setting
I have changed way you use setting. Here's a working snippet
$("#bugForm").submit((e) => {
e.preventDefault()
const input = document.getElementById('nameInput');
// logic here
const bugInfo = {
info: "Hello"
}
// changed here as I removed static
logger.logInfo(bugInfo).then(console.log('print'))
});
class Logger {
constructor(settings) {
// getting the settings here and assigning it to the constructor variable
this.settings = settings;
console.log('hello', this.settings)
}
// removed static
async logInfo(data = {}) {
console.log('Hello!')
const url = 'exampleUrl'
console.log(data);
console.log(this.settings)
const response = fetch(url, {
method: 'POST',
headers: {
// using it here while calling the method
"Token": `${this.settings.token}`,
"Content-Type": "application/json"
},
body: JSON.stringify(data)
});
return response.json();
}
}
const metadata = {
settings: {
token: 'hello'
}
}
const logger = new Logger(metadata.settings);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="bugForm">
<button type="submit">
Submit
</button>
</form>

Related

Graphql query variable is not updating in reactjs

I am building a simple single-page react website that uses two API's one is rest API and the second is GraphQl using simple hooks
What I am trying to do is:
first fetching the anime_chan data and passing the character name that I get from anime_chan data to GraphQl query search variable so that it gives me the data of that character
The flow I want is -
fetch rest API (anime_chan)
update the search variable in GraphQl query
fetch GraphQl API (ani_list)
set anime_chan_data
set ani_list_info
Problem is:
The GraphQl query search variable is never gets updated
Code
function App(){
const [variables, setVariables] = useState({
search:'lelouch'
});
// I also tried this
/* var variables = {
search: 'lelouch',
} */
console.log('before: '+ variables.search);
var query = `
query($search: String) {
Character(search: $search) {
name {
first
}
image {
large
medium
}
siteUrl
}
}`;
var ani_list_url = 'https://graphql.anilist.co',
options = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
query: query,
variables: variables
})
};
const anime_chan_url = 'https://animechan.vercel.app/api/random';
const [anime_chan_data, setAnime_chan_data] = useState({
loading:true,
data:{},
});
const [ani_list_info, setAni_list_info] = useState({});
const get_anime_chan_Data = async() =>{
const response = await fetch(anime_chan_url);
const anime_chan_data = await response.json();
console.log(anime_chan_data);
setAnime_chan_data({
loading:false,
data: anime_chan_data,
});
};
useEffect(() => {
get_anime_chan_Data();
setVariables({
search:anime_chan_data.character
});
console.log('After: '+ variables.search);
fetch(ani_list_url, options).then(handleResponse)
.then(handleData)
.catch(handleError);
function handleResponse(response) {
return response.json().then(function (json) {
return response.ok ? json : Promise.reject(json);
});
}
function handleData(info) {
console.log(info);
setAni_list_info(info);
}
function handleError(error) {
alert('Error, check console');
console.error(error);
}
}, []);
return (
<>...</>
}

Passing query string parameters in Lambda functions (Netlify)

I am trying to pass a query string into my serverless function but it keeps returning an empty object.
search = (searchTerm) => {
// let url = `${URL}${searchTerm}`;
return fetch(`/.netlify/functions/token-hider?search=${searchTerm}`)
.then((response) => response.json())
.then((result) => {
console.log(result.results);
return results;
});
form.addEventListener("submit", (e) => {
e.preventDefault();
let searchTerm = input.value;
search(searchTerm);
});
const axios = require("axios");
const qs = require("qs");
exports.handler = async function (event, context) {
// apply our function to the queryStringParameters and assign it to a variable
const API_PARAMS = qs.stringify(event.queryStringParameters.search);
console.log(event);
// const API_PARAMS = qs.stringify(event.queryStringParameters);
console.log("API_PARAMS", API_PARAMS);
// Get env var values defined in our Netlify site UI
// TODO: customize your URL and API keys set in the Netlify Dashboard
// this is secret too, your frontend won't see this
const { KEY } = process.env;
const URL = `https://api.unsplash.com/search/photos?page=1&per_page=50&client_id=${KEY}&query=${API_PARAMS}`;
console.log("Constructed URL is ...", URL);
try {
const { data } = await axios.get(URL);
// refer to axios docs for other methods if you need them
// for example if you want to POST data:
// axios.post('/user', { firstName: 'Fred' })
return {
statusCode: 200,
body: JSON.stringify(data),
};
} catch (error) {
const { status, statusText, headers, data } = error.response;
return {
statusCode: error.response.status,
body: JSON.stringify({ status, statusText, headers, data }),
};
}
};
it works when i hard code the query string, and i can console log the search term and it is defined.
Since Netlify redirect mechanism is not able to provide you the data of which rule it matched, you could try to match the original request in your function to determine what it should do.
Hope this helps you solve your specific issue!
Here is the reference

Uncaught (in promise) TypeError: Cannot set property of undefined at eval in vue.js?

I'm trying to set my empty object with the values I get from my server API, which is a json.
But I keep getting an error on the same row, over and over again:
Uncaught (in promise) TypeError: Cannot set property 'itemListModel' of undefined at eval
my code:
data: function() {
return {
itemListModel: {}
}
}
methods: {
getAllItemsFromDb: async () => {
const url = 'https://localhost:44339/ListAll';
await axios.get(url, {
headers: {
'Content-Type': 'application/json'
}}).then((response) => {
this.itemListModel = response.data
})
}
}
computed : {
itemResultsFromDB: function(){
return this.itemListModel
}
}
Looked att this previous question: Uncaught (in promise) TypeError: Cannot set property of undefined with axios
But I can't see what I am doing differently?
The arrow function is to blame, I believe. Convert getAllItemsFromDb to a function function:
methods: {
getAllItemsFromDb() {
const url = 'https://localhost:44339/ListAll';
axios.get(url, {
headers: {
'Content-Type': 'application/json'
}
}).then((response) => {
this.itemListModel = response.data
})
}
}
In your getAllItemsFromDb function you are awaiting the result of axios.get(). As a result you don't need the .then() block. Try this:
getAllItemsFromDb: async () => {
const url = 'https://localhost:44339/ListAll';
const response = await axios.get(url, {
headers: {
'Content-Type': 'application/json'
}
});
this.itemListModel = response.data;
}

Fetch returning TypeError: Type error on iPhone 5

I am having an issue making an API call on the iPhone 5.
I have the following API call made inside a component
import FavouritesService from "../../api/FavouritesService";
const Favourites = () => {
const getFavs = () => {
favouritesService.getFavourites(0, 10, "FULL").then(response => {
if (response.success === false) {
//...
} else {
//...
}
});
};
};
export default Favourites;
My FavouritesService that gets the api endpoint and calls a function inside an import is as follows.
import api from "./api";
class FavouriteService {
getFavourites(page, pageSize, view) {
return api.get(
"/api/social-groups?page=" +
encodeURIComponent(page) +
"&pageSize=" +
encodeURIComponent(pageSize) +
"&view=" +
encodeURIComponent(view) +
"&type=FAVOURITE"
);
}
}
export default FavouriteService;
My api.js file where I do the API itself is as follows...
import _ from "lodash";
import "babel-polyfill";
import "isomorphic-fetch";
function handleErrors(response) {
if (!response.ok) {
throw Error(response.statusText);
}
return response;
}
function handleFetchError(error) {
// Here is where I get TypeError: Type error
if (error) {
return { success: false, error: error };
}
}
function payloadOptions(method, body) {
var postBody = body;
var contentType = "application/x-www-form-urlencoded";
if (typeof postBody === "object") {
postBody = JSON.stringify(postBody);
contentType = "application/json";
}
return {
method: method,
body: postBody,
headers: {
"Content-Type": contentType
}
};
}
const defaultOptions = {
redirect: "error",
headers: {
Accept: "application/json"
}
};
class API {
request(url, options) {
return fetch(url, _.defaultsDeep(options || {}, defaultOptions))
.then(handleErrors)
.then(response => response.json())
.catch(handleFetchError);
}
get(url, options) {
return this.request(
url,
_.defaultsDeep(options || {}, payloadOptions("GET"))
);
}
}
export default new API();
This is where the error occurs in the handleFetchError, error returns TypeError: Type error. When I console.log this, that's all I get, I'm not able to drill down any further to actually inspect what's actually happened here.
I've tried to google this but no one else seems to have this specific issue so I assume I have gone wrong at some step when making this GET request.
Any help would be greatly appreciated as I have been stuck on this for some time.
I found that I had to use a polyfill to allow me to fetch.
This answer helped to figure out I had to install whatwg-fetch

How pass URL from API to Action (ReactJS)

Get API file
import { apiUrl } from '../config'
const baseUri = apiUrl
const uri = {
outline : '/course/income/outline'
}
const getURI = (key) => baseUri + uri[key]
module.exports = { apiMiddleware, get, post, put, ...{ delete: del }, uri, getURI }
Try pass this to my axios URL
import Api from '../middleware/api'
export function IncomeList () {
return dispatch => {
return (
axios.post(Api.getURI(outline),{}, {
headers: { 'X-Authenticated-Userid': '15000500000#1' }
}).then(function (response) {
console.log(response.data);
dispatch(receiveData(response.data.body));
})
.catch((error) => {
console.log(error);
})
)
}
}
But I get error Uncaught ReferenceError: outline is not defined. How to Pass correct URL ?
Pass string literal to getURI method:
Api.getURI('outline')
Calling Api.getURI(outline) makes interpreter look for outline variable, which is undefined in the current scope (hence ReferenceError).
Protip: linter, like ESLint, would catch this error early.

Categories