Quasar Q-table not updating with ref() array - javascript

When I update ref() array, q-table not updating.
I am initiating the rows ref with the "getApplications()" function.
Then when i call the reviewed() function from a line in the q-table, the table does not update with new data after i update the rows ref.
<q-table
v-model:selected="selected"
:loading="loading"
title="Applications"
:rows="rows"
:columns="columns"
row-key="id"
></q-table>
<script setup>
import { api } from "boot/axios";
import { ref } from "vue";
const columns = ref([ ........]);
let rows = ref([]);
getApplications();
function getApplications() {
api({
method: "get",
url: "/webdata/_partition/apply/_design/apply-list/_view/apply-list",
})
.then((response) => {
var row = fncArrayAll(response.data.rows);
rows.value = row;
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
}
function reviewed(prop) {
loading.value = true;
api({
method: "get",
url: "/webdata/" + prop.row._id,
})
.then((response) => {
var newData = response.data;
newData.office.reviewed = !newData.office.reviewed;
api({
method: "put",
url: "/webdata/" + prop.row._id,
data: newData,
})
.then((response) => {
console.log("new response: ", response);
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
})
.catch((e) => {
console.log("e: ", e);
alert(e);
})
.finally(() => {
loading.value = false;
});
}
function fncArrayAll(items) {
var filtered = [];
for (var i = 0; i < items.length; i++) {
filtered.push(items[i].value);
}
// console.log(filtered);
return filtered;
}
</script>
When rows is updated in the reviewed function, the q-table is not updated.
Thanks for any help

Related

django | Celery Async Task Result Pagination

I use celery and redis as backend for my async tasks. I like to paginate my results in the template.
I use Javascript (ajax Requests) to request the data.
Now I like to paginate the results also with Javascript after request the data.
I hope someone can help me.
Thats my javascript:
$(document).ready(() => {
console.log('Sanity Check!');
});
$('.button').on('click', function() {
$.ajax({
url: '/tasks/',
data: { type: $(this).data('type'),},
method: 'POST',
})
.done((res) => {
getStatus(res.task_id);
getStatusConfluence(res.task_id_confluence);
})
.fail((err) => {
console.log(err);
});
});
function getStatus(taskID) {
$.ajax({
url: `/tasks/${taskID}/`,
method: 'GET'
})
.done((res) => {
num_hosts = res.value.length
for (i=0; i < num_hosts; i++){
const html = `
<tr>
<td>${res.value[i]['name']}</td>
<td>${res.value[i]['OK']}</td>
<td>${res.value[i]['WARN']}</td>
<td>${res.value[i]['CRIT']}</td>
</tr>
`
$('#result').prepend(html);
}
const taskStatus = res.task_status;
if (taskStatus === 'SUCCESS' || taskStatus === 'FAILURE') return false;
setTimeout(function() {
getStatus(res.task_id);
}, 1000);
})
.fail((err) => {
console.log(err)
});
}
function getStatusConfluence(taskID) {
$.ajax({
url: `/tasks/${taskID}/`,
method: 'GET'
})
.done((res) => {
num_hosts = res.value.length
for (i=0; i < num_hosts; i++){
const html = `
<tr>
<td>${res.value[i]['title']}</td>
</tr>
`
$('#result_confluence').prepend(html);
}
})
.fail((err) => {
console.log(err)
});
}

trying to store api responses in asyncstorage but I am unable to store it

here I have pasted code which is written class component for mobx state management and i am calling it to another file,the thing is I have above 450 api responses and it need to store locally so i have tried it but i am not getting any value nor the data stored in database pls help me out thanks in advance ..
class ProductStore {
constructor() {
makeAutoObservable(this);
}
screenWidth = width;
screenHeight = height;
headerHeight = 0;
isiOS = Platform.OS === 'ios';
isAndroid = Platform.OS === 'android';
isProductLoading = 'pending';
productData = [];
filterdData = [];
search = '';
isFlatlistRender = false;
setFields(eName, data) {
this[eName] = data;
console.log(eName, data);
}
getproductData = () => {
if (this.isProductLoading == 'loading') {
return true;
}
this.isProductLoading = 'loading';
this.productData = [];
let headers = new Headers();
headers.set(
'Authorization',
'Basic ' + encode('username:password'),
);
fetch('some_url', {
method: 'GET',
headers: headers,
})
.then(response => response.json())
.then(responseJson => {
console.log('.....', responseJson);
AsyncStorage.setItem(
'ACCESS_TOKEN',
JSON.stringify(responseJson),
err => {
if (err) {
console.log('an error');
throw err;
}
console.log('success');
},
).catch(err => {
console.log('error is: ' + err);
});
try {
const value = AsyncStorage.getItem('ACCESS_TOKEN');
if (value !== null) {
console.log(JSON.parse(value));
}
} catch (error) {}
this.productData = responseJson;
this.isProductLoading = 'done';
})
.catch(error => {
console.error(error);
this.isProductLoading = 'error';
});
};
}
export default new ProductStore();
AsyncStorage.getItem() returns a promise, not the value. So, just add a then block after the line AsyncStorage.getItem('ACCESS_TOKEN');. It would be like this
AsyncStorage.getItem('ACCESS_TOKEN').then(value => {
if (value !== null) {
console.log(JSON.parse(value));
}
}).catch(err => console.error(err));

How to called async function in useEffect after submiting in react native?

I would like once the user click on the submit button for the whole "page" to reload and the useEffect function to be called. The current behavior is that when the user clicks the submit button, the useEffect function is not called at all. It is as if it does not reload directly after submission. I don't know if this is due to async and await. I give you the code :
useEffect() :
useEffect(() => {
console.log('test useEffect');
(async () => {
try {
const value = await AsyncStorage.getItem('authToken_Lust');
if(value !== null) {
const decodedValue = jwt_decode(value);
const current_time = Date.now() / 1000;
if(decodedValue.exp < current_time) {
setMessage('Vous n\'êtes plus connecté(e).')
} else {
setMessage('Vous êtes connecté(e)');
}
}
} catch(err) {
console.log(err);
}
})();
}, []);
The code of the function called after the user clicks submit :
const onSubmit = async () => {
setLoading(true)
await fetch('http://192.168.1.36:3000/api/users/login', {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: email,
password: password
})
})
.then((response) => response.json())
.then(async (res) => {
if(res.error) {
setMessage(res.error);
} else {
try {
await AsyncStorage.setItem('authToken_Lust', res.token);
} catch (err) {
console.log(err);
}
}
})
.catch((err) => console.log(err))
.finally(() => setLoading(false));
}
Tanks
Create a state variable to indicate that credentials have been successfully submitted (within this component).
const [submitted, setSubmitted] = useState(1);
Alter this state variable whenever you get a response from your api in onSubmit (to somehow update the component):
try {
await AsyncStorage.setItem('authToken_Lust', res.token);
setSubmitted(submitted+1);
}
Remove the dependency array from your useEffect altogether or change it to respond to submitted value changes;
useEffect(() => {
// ...
}, [submitted]);
you need to make these changes to your codes:
const onSubmit = () => {
setIsSubmitted(true);
setLoading(true);
fetch("http://192.168.1.36:3000/api/users/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then((response) => response.json())
.then(async (res) => {
if (res.error) {
setMessage(res.error);
} else {
try {
await AsyncStorage.setItem("authToken_Lust", res.token);
} catch (err) {
console.log(err);
}
}
})
.catch((err) => console.log(err))
.finally(() => setLoading(false));
};
const asyncEffect = async () => {
try {
const value = await AsyncStorage.getItem("authToken_Lust");
if (value !== null) {
const decodedValue = jwt_decode(value);
const current_time = Date.now() / 1000;
if (decodedValue.exp < current_time) {
setMessage("Vous n'êtes plus connecté(e).");
} else {
setMessage("Vous êtes connecté(e)");
}
}
} catch (err) {
console.log(err);
}
};
useEffect(() => {
if (isSubmitted) {
console.log("test useEffect");
asyncEffect();
}
}, [isSubmitted]);
I changed all my code taking into account your advice that gives :
const [submitted, setSubmitted] = useState(1);
useEffect(() => {
console.log("test useEffect");
asyncEffect();
}, [submitted]);
const asyncEffect = async () => {
try {
const value = await AsyncStorage.getItem("authToken_Lust");
if (value !== null) {
const decodedValue = jwt_decode(value);
const current_time = Date.now() / 1000;
if (decodedValue.exp < current_time) {
setMessage("Vous n'êtes plus connecté(e).");
} else {
setMessage("Vous êtes connecté(e)");
}
}
} catch (err) {
console.log(err);
}
};
const onSubmit = () => {
setSubmitted(submitted+1);
setLoading(true);
fetch("http://192.168.1.36:3000/api/users/login", {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
body: JSON.stringify({
email: email,
password: password,
}),
})
.then((response) => response.json())
.then(async (res) => {
if (res.error) {
setMessage(res.error);
} else {
try {
await AsyncStorage.setItem("authToken_Lust", res.token);
} catch (err) {
console.log(err);
}
}
})
.catch((err) => console.log(err))
.finally(() => setLoading(false));
};
When I click on the submit button, the console log works fine (I get "test useEffect" on console) but the asyncAffect() function does not seem to be called.
The setMessage in asyncEffect () don't change at all.

I can not fetch a post in JavaScript

I have a question about the code. Probably the solution is very simple, but I'm taking the first step in JavaScript and it is not obvious to me.
I have some backend ready, postman sending POST is ok. So backend is fine.
I wrote a simple application in which after pressing the button saves the given data in the database.
Unfortunately, this doesn't work with the debugger, everything is fine. However, by clicking the button in the view something is wrong and no fetch is called. The object is not saving to the database.
Please help.
Api = function() {
this.header = new Headers({
'Accept': 'application/json',
'Content-Type': 'application/json'
})
};
Api.prototype.buildUrl = function(id) {
return "http://localhost:3000/db/shop_name/" + id;
};
Api.prototype.post = function(id, data) {
const urlPost = api.buildUrl(id.value);
return fetch(urlPost, {
method: "post",
body: JSON.stringify(data),
headers: this.header
})
.then(res => res.json())
.then(res => {
console.log("Dodałem użytkownika:");
console.log(res);
})
};
Api.prototype.get = function(id) {
//const urlGet = api.buildUrl(id);
return fetch(id, {
method: "GET",
})
.then(resp => {
alert(resp.json());
return resp.json();
})
};
Api.prototype.getAlll = function() {
return fetch(url, {
method: "GET"
})
.then(resp => {
alert(resp.json());
return resp.json()
})
};
Api.prototype.update = function(id, data) {
const url = api.buildUrl(id);
return fetch(url, {
method: "PUT",
body: JSON.stringify(data)
})
.then(resp => {
return resp.json()
.catch(error => {
let notFound = "The server can not find requested resource";
document.getElementById("stars").innerHTML = notFound + error.status;
})
})
};
Api.prototype.addProduct = function(id, data) {
return this.post(id, data);
};
Api.prototype.deleteProduct = function(id) {
return this.delete(id);
};
Api.prototype.updateProduct = function(id, data) {
return this.update(id, data);
};
Api.prototype.getProduct = function(id) {
return this.get(id);
};
Api.prototype.getAllProducts = function() {
return this.getAlll;
};
const Main = function() {
this.id = document.getElementById("id");
this.addCount = document.getElementById("count");
this.addName = document.getElementById("name");
this.addPrice = document.getElementById("price");
};
Main.prototype.add = function() {
// const ido = this.id.value;
const data = {
"price": this.addPrice.value,
"name": this.addName.value,
"count": this.addCount.value,
};
// let id = api.buildUrl(this.id.value);
api.addProduct(this.id, data);
};
Main.prototype.update = function() {
const data = {
"price": this.price,
"name": this.name,
"count": this.count,
};
api.updateProduct(id, data);
};
Main.prototype.delete = function() {
let id = api.buildUrl(this.id);
api.deleteProduct(id);
};
Main.prototype.get = function() {
let id = api.buildUrl(this.id.value);
api.getProduct(id);
};
Main.prototype.getAll = function() {
api.getAllProducts();
};
const api = new Api();
const main = new Main();
let addButton = document.getElementById('postBtn');
addButton.addEventListener('click', function() {
main.add();
});
/*
addButton.addEventListener("click",main.add.bind(main));
*/
let updateButton = document.getElementById("updateBtn");
updateButton.addEventListener("click", function() {
main.update();
});
let deleteButton = document.getElementById("deleteBtn");
deleteButton.addEventListener("click", function() {
main.delete();
});
let getButton = document.getElementById("getBtn");
getButton.addEventListener("click", function() {
main.get();
});
let getAllButton = document.getElementById("getAllBtn");
getAllButton.addEventListener("click", function() {
let tst = main.getAll();
console.log(tst);
});

javascript/react/redux async await refactoring

I would like to refactor the fetchRelationships function to use async await. I am not sure what the best way is to do it as this code contains nested .then at response.json().then((json) =>....
Could sby pls post the refactored version?
export const fetchRelationshipsError = (error) => {
return {
type: FETCH_RELATIONSHIPS_FAILURE,
payload: { error }
};
};
export const fetchRelationshipsRequest = () => {
return { type: FETCH_RELATIONSHIPS_REQUEST };
};
export const fetchRelationshipsSuccess = (relationships) => {
return {
type: FETCH_RELATIONSHIPS_SUCCESS,
payload: relationships
};
};
export const fetchRelationships = (url) => {
return (dispatch) => {
dispatch(fetchRelationshipsRequest());
fetch(url, config)
.then((response) => {
const responseObj = {
response: response,
payload: response.json().then((json) => {
return { body: json }
})
};
if (!response.ok) {
const error = new Error(response.statusText);
responseObj.payload.then((response) => {
show_error_alert(response.body);
dispatch(fetchRelationshipsError(response.body));
});
throw error;
}
return responseObj.payload;
})
.then((response) => {
dispatch(fetchRelationshipsSuccess(response.body))
})
.catch((error) => { console.log('Request failed', error); });
};
};
Solution:
export const fetchRelationships = (url) => {
return async (dispatch) => {
dispatch(fetchRelationshipsRequest());
try {
const response = await fetch(url, config);
const jsonResponse = await response.json();
if (!response.ok) {
show_error_alert(jsonResponse);
dispatch(fetchRelationshipsError(jsonResponse));
const error = new Error(response.statusText);
throw error;
}
dispatch(fetchRelationshipsSuccess(jsonResponse));
} catch(error) {
console.log('Request failed', error);
}
};
};
Ill take a stab at this:
export const fetchRelationshipsError = (error) => {
return {
type: FETCH_RELATIONSHIPS_FAILURE,
payload: { error }
};
};
export const fetchRelationshipsRequest = () => {
return { type: FETCH_RELATIONSHIPS_REQUEST };
};
export const fetchRelationshipsSuccess = (relationships) => {
return {
type: FETCH_RELATIONSHIPS_SUCCESS,
payload: relationships
};
};
export const fetchRelationships = (url) => {
return async (dispatch) => {
dispatch(fetchRelationshipsRequest());
try{
const response = await fetch(url, config)
const jsonResponse = await response.json()
if(!response.ok){
show_error_alert(jsonResponse);
dispatch(fetchRelationshipsError(jsonResponse));
const error = new Error(response.statusText);
throw error;
}
dispatch(fetchRelationshipsSuccess(jsonResponse));
}catch(error){
console.log('Request failed', error);
}
};

Categories