I do a get in the api and I can collect their data but when I assign it to a data variable it doesn't get it
data() {
return {
departamento: [],
}
},
setup() {
onMounted(() => {
const token = setToken.getToken();
axios
.get("https://sig-fpto.herokuapp.com/api/departamentos/buscarTodos", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(response.data);
this.departamento = response.data
})
.catch((err) => console.log(err.response));
})
You are mixing Vue2 syntax with Vue3. Here is what should work:
setup() {
const departamento = ref([]);
onMounted(() => {
const token = setToken.getToken();
axios
.get("https://sig-fpto.herokuapp.com/api/departamentos/buscarTodos", {
headers: {
Authorization: `Bearer ${token}`,
},
})
.then((response) => {
console.log(response.data);
departamento.value = [...response.data];
})
.catch((err) => console.log(err.response));
})
return {
departamento,
}
}
I have an app that does many API calls, but I release each and every connection like this?
app.put("/interview/create/questions/:lastEmployeeId", function (req, res) {
console.log("It is getting to the route");
const employee_id = req.body.lastEmployeeId;
const tableName = req.body.table;
connection.getConnection(function (err, connection) {
connection.query(
`INSERT INTO ${tableName} (employee_id)
VALUES (?)`,
[employee_id],
function (error, results, fields) {
if (error) throw error;
res.json(results);
console.log(`Interview has been created`);
}
);
connection.release();
});
});
Is this the correct way, because I'm getting a lot of inconsistent 502 and 503 errors. It feels to me like maybe it's running out of resources. The paths are correct, because sometimes they work, and sometimes they don't. It's random, so I can't figure out what to do.
Doesn't the connection.release() free up the resources? I currently have the max connections set to 50, which should be more than I need because only one person at a time will be using this, and there is a method where it makes 8 calls. I wouldn't mind some help refactoring this, but I still need this many calls I believe because I need it to create rows in 8 different tables. This long method below here is just taking a value entered in one table, and entering it as a reference in the 8 other tables.
createQuestions() {
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_general",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_culture",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_performance",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_policies",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_risk",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_strategy",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_rewards",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
)
.then(
fetch(
API_URL + `/interview/create/questions/${this.state.lastEmployeeId}`,
{
method: "PUT",
body: JSON.stringify({
lastEmployeeId: this.state.lastEmployeeId,
table: "audit_workforce",
}),
headers: { "Content-Type": "application/json" },
}
)
.then((res) => {
if (!res.ok) {
throw new Error();
}
return res.json();
})
.then((data) => console.log(data))
.catch((err) => console.log(err))
);
}
You're releasing the connection before the query completes. This needs to be addressed:
app.put("/interview/create/questions/:lastEmployeeId", function (req, res) {
console.log("It is getting to the route");
const employee_id = req.body.lastEmployeeId;
const tableName = req.body.table;
connection.getConnection(function (err, connection) {
if (err) {
res.statusCode = 500;
res.send('DB connection could not be acquired.');
return;
}
connection.query(
`INSERT INTO ${tableName} (employee_id)
VALUES (?)`,
[ employee_id ],
function (error, results, fields) {
// throw here does nothing useful, it's inside a callback and
// the calling function may have terminated ages ago. You need
// to handle this error here and now.
if (error) {
res.statusCode = 500;
res.send('Nope!');
return;
}
res.json(results);
console.log(`Interview has been created`);
// Now you can release the handle
connection.release();
}
);
// Code here runs before the query can complete.
});
});
Think of your asynchronous program flow like this:
connection.getConnection(..., cbGC) executes and returns
** Long time passes
cbGC executes -> connection.query(..., cbQ) executes and returns
** Tiny eternity elapses
cbQ executes!
The time interval between calling a function that takes a callback and that callback actually executing can be significant, seconds or more, which means the calling function is not only dead, it is ancient history, probably garbage collected.
You need to organize your code around this principle of nesting anything that depends on that sequencing.
whenever I click the delete button its works fine but I don't get the output like " deleted successfully " its shows .then undefined..
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
if (data.error) {
console.log(data.error);
} else {
preload();
}
});
};
here is the delete category API call
export const deleteCategory = (userId, categoryId , token) => {
fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
},
})
.then(response => {
return response.json();
})
.catch(err => console.log(err));
};
It should be like this. deleteCategory needs to send only promise. Later where ever you are resolving you have to use then.
export const deleteCategory = (userId, categoryId , token) => {
return fetch(`${API}/category/${categoryId}/${userId}`, {
method: "DELETE",
headers: {
Authorization: `Bearer ${token}`,
"Content-Type":"application/json"
}
})
};
const deleteThisCategory = (CategoryId) => {
deleteCategory(CategoryId, user._id, token).then(data => {
preload();
}).catch(err => {
console.log(err);
})
};
I am trying to fetch data from a Socrata API and then post it to my own database. When I run the function in node, I get the error "ReferenceError: fetch is not defined"
I am totally lost, and am wondering how to pull this off. I have been googling for the past four hours, and can't find anything.
My code:
const apiURL = "https://ftbserver.herokuapp.com/npos"
const soda = require('soda-js');
var consumer = new soda.Consumer('data.colorado.gov');
let stuff
consumer.query()
.withDataset('p3jp-z4tq')
.limit(2)
.where({ principalcity: 'Denver' })
// .order('namelast')
.getRows()
.on('success', function (rows) {
rows.map((nposNew) => {
let data = {
fein: nposNew.fein,
name: nposNew.name,
revenuetotal: nposNew.revenuetotal,
expensestotal: nposNew.expensestotal
}
fetch(apiURL, {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: JSON.stringify(data)
})
.then(response => response.json())
.then(response => {
showSuccess(response.message)
setTimeout(() => (removeMsg()), 4000);
})
.catch(console.error);
})
})
.on('error', function (error) { console.error(error); });
// console.log(stuff);
// console.log(npost);
I used two classes
I call the second class as below
let s = new SearchExtend();
output = s.fetchData(search)
alert(output)
The second function:
fetchData = (search) => {
fetch('http://example.com/search.php' , {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
// Getting the search.
search: search
})
}).then((response) => response.json())
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(error);
});
}
But i get in "alert" undefined
When I use this.setState instead of return, I get the following error:
warning setstate(...) can only update a mounted or mounting component
You are getting undefined because you are using promises. Initially it returns undefined and once promise is resolved you get the actually data.
A better way to handle this would be to return the promise and resolve it externally as follows:-
const fetchApi = () => {
return fetch("https://swapi.co/api/people" , {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).then((response) => {
return response.json();
})
.then((responseJson) => {
return responseJson;
})
.catch((error) => {
console.error(JSON.stringify(error));
});
}
fetchApi()
.then((data) => {
console.log("data", data);
})