Having pagination issue in Vue / Laravel - javascript

Trying to paginate fetched data in Vue. But having a problem:
Question Updated
Error in render: "TypeError: this.estates.filter is not a function"
Do I missing something?
Pagination.vue
Data(){
return {
meta_data: {
last_page: null,
current_page: 1,
prev_page_url: null
}
}
},
mounted() {
this.fetchEstates();
},
methods: {
fetchEstates(page = 1) {
axios.get('/ajax', {
params: {
page
}}).then((response) => {
this.estates = response.data;
this.meta_data.last_page = response.data.last_page;
this.meta_data.current_page = response.data.current_page;
this.meta_data.prev_page_url = response.data.prev_page_url;
});
}
},
computed: {
one: function () {
let filteredStates = this.estates.filter((estate) => {
return (this.keyword.length === 0 || estate.includes(this.keyword)) &&
(this.rooms.length === 0 || this.rooms.includes(estate.rooms)) &&
(this.regions.length === 0 || this.regions.includes(estate.region))});
/// rest of the code....
if you need more information please tell me.

You should change the line
this.estates = response.data;
to
this.estates = response.data.data;

$data = \DB::table('allestates')->paginate(5);
$response = [
'pagination' => [
'total' => $data->total(),
'per_page' => $data->perPage(),
'current_page' => $data->currentPage(),
'last_page' => $data->lastPage(),
'from' => $data->firstItem(),
'to' => $data->lastItem()
],
'data' => $data
];
return response()->json($response);

Related

pass an argument from axios to a method vue

I'm new to vue and I'm trying to make this work. I get some data from a XML, everything works, but I want to change which value I get from XML using a computed which gets a value from Store.
My computed is:
currentStep: {
set (val) {
this.$store.commit('setCurrentStep', val)
},
get () {
return this.$store.state.currentStep
}
}
With axios and xml2js I get all data with this Method:
getData() {
axios.get("https://something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, function (err, result) {
let obj = null
obj = result.flugplan.abflug[0].flug;
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString(),
})
}
resolve(flight_dates);
})
})
}
I need to change my OBJ using my computed like:
let obj = null
if (this.currentStep === 'departures') {
obj = result.flugplan.abflug[0].flug;
} else {
obj = result.flugplan.ankunft[0].flug;
}
But it does not work. Can you guys please help ?
Thank you very much.
Computed can only return some value instead of modifying anything.
Try this one:
computed: {
someData() {
return this.currentStep === 'departures' ? result.flugplan.abflug[0].flug : result.flugplan.ankunft[0].flug;
}
}
After that use a someData value:
const obj = this.someData
I get it finally and now works! here is the code, if someone have the same issue
getData() {
axios.get("something.xml").then((response) => {
this.parseXML(response.data).then((data) => {
this.flightInformations = data
})
.catch(err => {
console.log(`${err} data is not avaiable`)
})
})
},
parseXML(data) {
return new Promise((resolve) => {
let parser = new xml2js.Parser({
trim: true,
explicitArray: true,
});
parser.parseString(data, (err, result) => {
let obj = null
if (this.$store.state.currentStep === 'abflug') {
obj = result.flugplan.abflug[0].flug
} else {
obj = result.flugplan.ankunft[0].flug
}
let flight_dates = {};
for (let item of obj) {
let flight_date = item.datum.join().toString();
if (!flight_dates[flight_date]) {
flight_dates[flight_date] = [];
}
flight_dates[flight_date].push({
flightNr: item.flugnr.join().toString(),
flightPlace: item.ort.join().toString(),
flightPlan: item.plan.join().toString(),
flightExpected: item.erwartet.join().toString(),
flightDate: item.datum.join().toString()
})
}
resolve(flight_dates)
})
})
}
Now using Store, when I change my CurrentStep, it also changes which part of XML it reads.

how to run useEffect only twice

Here is My useEffect is going in Infinite loop, becouse checkimage value is changing becouse the value is assigned in fetch(), so anyone know how to solve it. I want to get varient data with image but I can't get it in first time.
help me if you can
Thank You
useEffect(() => {
fetch({ pagination });
}, [checkimage]);
const fetch = async (params = {}) => {
if (type == 'product') {
dispatch(await ProductService.getProduct(productId))
.then((res) => {
let variantsdatas = getImageArns(res.data.variants);
getImages(variantsdatas);
let record = [];
record.push(res.data)
setVarientsData(record)
})
.catch((err) => {});
} else {
dispatch(await ProductService.getProducts())
.then((res) => {
console.info({ 'res.data': res.data });
setVarientsData(res.data.products);
setPagination({
...params.pagination,
total: res.total_count,
});
})
.catch((err) => {});
}
};
const getImageArns = (variantsdatas) => {
const variantImageArns = [];
variantsdatas.forEach((variant, index) => {
variant[index] = variant.variantId;
if (variant.variantImagesListResponseDto.images.length > 0) {
let variantImageObj = {
variantId: variant.variantId,
arnUrl: variant.variantImagesListResponseDto.images[0].docUrl,
};
variantImageArns.push(variantImageObj);
}
});
// console.info('id', variantImageArns);
return variantImageArns;
};
const getImages = async (variantsdatas) => {
const images = [];
dispatch(await ProductVariantService.getImage(variantsdatas))
.then((res) => {
console.info(res.data.fileResponseDtoList);
let presignedURLs = {};
res.data.fileResponseDtoList.map(
(i) => (
(presignedURLs = {
variantId: i.variantId,
arnUrl: i.presignedURL,
}),
console.info(presignedURLs),
images.push(presignedURLs)
)
);
setcheckimage(images);
})
.catch((err) => {
console.info('Get Error District...');
});
};
var img = 'img';
const setVarientsData = (products) => {
let varients_array = [];
if (products.length > 0) {
products.forEach((product) => {
if (product.variants.length > 0) {
let product_varients = product.variants;
product_varients.forEach((varient) => {
for (var f = 0; f < checkimage.length; f++) {
if(checkimage[f].variantId == varient.variantId){
img = checkimage[f].arnUrl;
f = checkimage.length
}
else{
img = 'img2';
}
}
varients_array.push({
image: img,
variantId: varient.variantId,
productVariantName: varient.variantName,
productName: product.productName,
brand: '-',
sellerSku: varient.productVariantCode,
status: product.status,
category: product.subCategoryInfo.categoryInfo.categoryName,
subCategoryName: product.subCategoryInfo.subCategoryName,
state: '-',
market: '-',
mrp: varient.price.amount + ' ' + varient.price.currency,
sellingPrice: '-',
manufacturer_product_variant_code:
varient.manufacturerProductVariantCode,
product_varient_code: varient.azProductVariantLongCode,
hsnCode: varient.hsnCode,
});
});
}
});
}
setVarients(varients_array);
console.info('varients_array ====>>', {varients_array})
};
I think that if I stop to run blow code getImage function then I can get my result
am I right?
But I tried It too but is also not happening properly.
a quick and dirty fix could be to work with a counter.
and only run the fetch in the useEffect, when counter is 0.
have you tried that?

How I can make asynchronous queries in GraphQL?

I'm calling 1 query and mutation. Mutation works fine, but when I get response from my query I need to redirect user to another page, but In my case, the function is triggered before I get response. How can I prevent this?
const renderData = async () => {
const currentUserId = await data?.signInUserSession?.idToken
?.payload?.sub;
const isAdmin = await data?.signInUserSession?.idToken?.payload[
"custom:role"
];
localStorage.setItem("userId", currentUserId);
if (
currentUserId !== null &&
currentUserId !== undefined &&
currentUserId !== ""
) {
Auth.currentSession().then((data) => {
setData({
variables: {
updateUserInput: {
id: currentUserId,
firstName: data.getIdToken().payload.given_name,
lastName: data.getIdToken().payload.family_name,
},
},
});
});
isCodeValid({
variables: {
validateUserVerificationCodeInput: {
user: {
id: currentUserId,
},
},
},
});
if (isAdmin === "admin" && isUserCodeValid) {
history.push("/managements");
} else if (
isUserCodeValid !== undefined &&
isUserCodeValid === true
) {
history.push("/verification");
} else if (isUserCodeValid) {
history.push("/stripe");
}
}
};
isUserCodeValid - is a response from query
useMutation has onCompleted and refetchQueries options for such cases. It is hard to write an exact solution for your case since not all code is visible but an example like below can help, I believe:
const [addProduct, { data, loading, error }] = useMutation(
createProductMutation
);
const onFinish = async (fieldNames) => {
await addSpending({
variables: { ...others, ...fieldNames},
refetchQueries: [{ query: calledQuery }],
onCompleted: (data) => {
// your logic
},
});
if (!error) {
form.resetFields();
onFinishSave(true);
}
};

How to unit test JSON result in Jest NodeJS?

my function i am trying to unit test is given as
NOTE : mypayload= payload.Items i will give a JSON reference at the end of the question
function setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty(mypayload) {
let _res = mypayload.map(ele => {
if (ele.id == null) {
ele.id = ele.deviceId
}
if (ele.id == null && ele.deviceId == null) {
ele.id = '***Both id and device id is null***'
}
if (ele.ssid == null) {
ele.ssid = '***ssid is null***'
}
if (ele.deviceName == null) {
ele.deviceName = '**deviceName is null**'
}
return ele;
})
return _res
}
I am trying to test the most basic part that is the first if loop ele.id==null
I have tried :
describe('Test setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty', () => {
test('testing null', () => {
index.setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty(mypayload)
mypayload.map(ele => {
if (ele.id == null) {
expect(ele.id).toEqual(ele.deviceId)
}
})
})
})
However i cannot get this test case to fail for ex if i enter expect(ele.id).toEqual("random") it still passes when i am expecting it to fail,Clearly i am doing something wrong
Reference
const payload = {"Items":[
{
"id" :"mycompany-00b12396",
"ssid": "home",
"deviceName": "mydevice",
"time": "0.753235299 Hours"
},
{
"ssid": "office",
"deviceName": "thisdevice",
"time": "12.52115515 Hours",
"deviceId":"mycompany-0031f13"
}
]}
You should test the result of the function like this:
describe('Test setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty', () => {
test('testing null', () => {
const result = index.setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty(mypayload)
result.map(ele => {
if (!ele.id) {
expect(ele.id).toEqual(ele.deviceId)
}
})
})
})
I have been trying and this worked for me hope it helps someone in the future
describe('Test setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty', () => {
test('testing null', () => {
const result = index.setIdtoDeviceIdIfEmptyAndSetNullIfFieldEmpty(mypayload)
let check = result.find(el => el.deviceId === "mycompany-00a412f");
expect(check.id).toEqual(check.deviceId)
})
})

Searching For Nested Object in Angular

I have a problem searching for a nested array in my Angular app. I have to access the package.name. Please help thanksenfoiewfhfofhfowfoewhfowfoewhfwefwfhowefweofhew8ofwofhewofw8eofhwf
JSON
[{
"id": 1,
"name": "Yeah",
"package_id": 1,
"price": 100,
"package": {
"id": 1,
"name": "Yeah"
}
}]
TS
search(event) {
const val = event.target.value.toLowerCase();
if (!val) {
this.users = this.tempUsers;
}
const temp = this.tempUsers.filter((row) => {
return Object.keys(row).some((property) => {
return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
});
});
this.users = temp;
}
TS
getAllUsers() {
this.usersService.getAll()
.subscribe(
(data: any) => {
console.log(data);
this.users = data.Users;
this.tempUsers= [...this.users];
},
error => {
console.log(error);
});
}
Does this work for you,
const temp = this.tempUsers.filter((row) => {
return Object.keys(row).some((property) => {
if (property === 'package') {
// check package.name value here
// like return row[property].name === 'something' ? true : false;
} else {
// the rest of the outer properties can be checked here
// not modifying your code here, but make sure it works for you
return row[property] === null ? null : row[property].toString().toLowerCase().indexOf(val) !== -1;
}
});
});
I have only answered your question on how to access the nested object inside the array method. Hope it helps or gives you an idea to fine tune your solution.
According to your data, You can use the following filter;
const filteredData = data.filter((item) => item.price.toString() === val || item.package_id.toString() === val || item.package.name.toString().toLowerCase().indexOf(val) !== -1 );
// UPDATED WITH CODE
search(event) {
const val = event.target.value.toLowerCase();
const filteredData = this.users.filter((item) => item.price.toString() === val ||
item.package_id.toString() === val ||
item.package.name.toString().toLowerCase().indexOf(val) !== -1 );
this.users = filteredData ;
}

Categories

Resources