How to initialize data correctly in vue js? - javascript

It takes the initTableData and initTableFiltered after onChangeDistrict which i hope to not take it now, instead to take only the initTableFiltered
data () {
return {
data: []
}
},
created () {
this.initTableData()
},
methods() {
initTableData () {
db.collection('example').orderBy('owner_name', 'asc').get().then(res => {
res.forEach((doc) => {
this.data.push({
id: doc.id,
})
})
})
},
initTableFiltered () {
db.collection('filter').orderBy('name', 'asc').get().then(res => {
res.forEach((doc) => {
this.data.push({
id: doc.id,
})
})
}
onChangeDistrict () {
this.initTablefiltered()
}
}
So how to initialize the initTablefiltered freshly on onChangeDistrict?

Did you create data variable? This isn't in the code?
Ex:
export default {
data() {
return {
data: []
}
},
...
Without instantiate your data, this is not reactive...

Related

apollo client offsetLimitPagination not working

I have a hook..
export function useLazyProposalList() {
const [getQueueData, { loading, data, error, fetchMore }] = useLazyQuery(PROPOSAL_LIST, {
fetchPolicy: 'no-cache',
});
const proposalList = React.useMemo(() => {
if (!data) {
return null;
}
return transformProposals(data);
}, [data]);
return {
getQueueData,
fetchMore,
loading,
data: proposalList,
error,
};
}
In the component
const {
getQueueData,
data: queueData,
fetchMore: fetchMoreProposals,
// loadMore: loadMore,
} = useLazyProposalList();
If user clicks on fetch more button, I call: fetchMoreProposals .
await fetchMoreProposals({
variables: {
offset: visibleProposalList.length,
},
});
but this doesn't update my data. I read that we should use offsetLimitPagination, but my data from query is not array itself. It's like this: queue { id: '1', items:[] } and because of this, offsetLimitPagination doesn't work. So I tried merge
cache: new InMemoryCache({
typePolicies: {
Query: {
fields: {
queue: {
keyArgs: false,
merge(existing, incoming) {
console.log(existing, incoming);
if (!incoming) return existing;
if (!existing) return incoming;
},
},
},
},
}
but in the console, it just prints refs instead of real data.
What could be the issue ?

I cannot implement a filter to my array in vue.js

I've been looking for quite a while but being a novice I can't find an answer.
I would like to filter my array with the id of a property I think is the wrong syntax.
Thanks for your help
components
export default {
props: ["user", "recette"],
data() {
return { email: this.$route.params.email };
},
components: {},
methods: {},
computed: {
filteredItems: function () {
return this.recette.filter((recettes) => {
return recettes.cat_recetteId === 1;
});
},
},
};
VIEW
<template>
<div>
<myrecette :recette="recette"/>
<myfooter />
</div>
</template>
<script>
import myrecette from "../components/recette";
import myfooter from "../components/myfooter";
export default {
name: "",
data() {
return {
recette: "",
user: "",
};
},
components: {
myrecette,
myfooter,
},
created: function() {
this.axios.get("http://localhost:3000/recette/all_recette/").then((res) => {
(this.recette = res.data.recette),
this.axios
.get(
"http://localhost:3000/user/rec_user/" + this.$route.params.email
)
.then((res) => {
this.user = res.data.user;
});
});
},
};
</script>
<style scoped></style>
NODE
router.get("/all_recette", (req, res) => {
db.recette
.findAll({
include: { all: true },
})
.then((recette) => {
if (recette) {
res.status(200).json({
recette: recette,
});
} else {
res.json("il n'y a pas de recettes");
}
})
.catch(err => {
res.json(err);
});
});
Here is my complete code as well as my node route.
My error return is
vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: this.recette.filter is not a function"
The filter works by keeping items which return true, so if you want all items having a cat_recetteId of 1, you would change it to:
computed: {
filteredItems: function() {
if (!this.recette) return [];
return this.recette.filter((recettes) => {
return recettes.cat_recetteId === 1;
});
},
},
It's also good practice to use an arrow function in most cases inside of a computed.
Your filter callback function should return true or false. You're 1) not returning anything and 2) assigning a value (=) instead of doing a comparison (==/===).
computed: {
filteredItems: function() {
return this.recette.filter(function(recettes) {
return recettes.cat_recetteId === 1;
});
},
},

Vue.js this is undefined inside computed property

I have following input tag with model selectedProp:
<input type="text" v-model="selectedProp" />
and I want to iterate through items like this:
<div v-for="item of filteredItems">{{item.prop}}</div>
Here's the script for the component:
export default {
name: 'App',
data() {
return {
items: [],
selectedProp: "",
projects: [],
errors: []
}
},
created() {
axios.get(`${URL}`)
.then(response => {
// JSON responses are automatically parsed.
this.items = response.data;
})
.catch(e => {
this.errors.push(e)
});
},
computed: {
filteredItems() {
if(this.selectedProp) {
console.log(this.selectedProp);
return this.items.filter(function (item) {
return item.prop == this.selectedProp;
});
}
return this.items;
}
},
}
Error
this is undefined inside computed property
In this case you could use arrow function which has access to this object
return this.items.filter( (item)=> {
return item.prop == this.selectedProp;
})

Trying to use this.props.dispatch and returns that is not a function

I am trying to delete an item from DB but when I access the function is saying _this.props.dispatch is not a function. (In '_this.props.dispatch((0, _actions.deleteJob)(_this.props.id))', '_this.props.dispatch' is undefined)
Here is my code where I am calling the function to delete my item. The function onDelete() I am calling it after user interaction.
class JobItem extends Component {
constructor(props) {
super(props)
this.state = {
activeRowKey: null,
deleting: false
};
}
onDelete = () => {
this.setState({deleting: true});
this.props.dispatch(deleteJob(this.props.id)); // HERE is the error
}
render() {
const swipeSettings = {
autoClose: true,
onClose: (secId, rowId, direction) => {
this.setState({ activeRowKey: null });
},
onOpen: (secId, rowId, direction) => {
this.setState({ activeRowKey: this.props.id });
},
right: [
{
onPress: () => {
const deletingRow = this.state.activeRowKey;
Alert.alert(
'Alert',
'Are you sure you want to delete?',
[
{text: 'No', onPress: () => console.log('Cancel Pressed'), style:'cancel'},
{text: 'Yes', onPress: () => {
this.onDelete();
// Refresh Job List
this.props.parentFlatList.refreshJobList(deletingRow);
}},
],
{ cancelable: true }
)
},
text: 'Delete', type: 'delete'
}
],
rowId: this.props._id,
sectionId: 1
}
And here is the deleteJob() function where it actually delete it from DB
export function deleteJob(job_id) {
return function (dispatch) {
return axios.delete(JOB_URL(user_id, job_id), {
headers: { authorization: token }
}).then((response) => {
dispatch(removeJob(job_id));
}).catch((err) => {
dispatch(addAlert("Couldn't delete job."));
});
};
}
JobItem
var renderJobs = () => {
return this.props.jobs.map((job) => {
return (
<JobItem
parentFlatList={this}
key={job._id}
title={job.title}
shortDescription={job.shortDescription}
logo={job.avatar}
company={job.company}
id={job._id}/>
)
})
}
var mapStateToProps = (state) => {
return {
jobs: state.jobs
}
}
module.exports = connect(mapStateToProps)(JobList);
Any idea how shall I solve this?
I think you forgot to pass dispatch to JobItem
<JobItem
parentFlatList={this}
key={job._id}
title={job.title}
shortDescription={job.shortDescription}
logo={job.avatar}
company={job.company}
id={job._id}
dispatch={this.props.dispatch} /* <-- this one here */
/>
One way to fix the problem is to put JobItem inside container.
Something like this
module.exports = connect(mapStateToProps,dispatch=>({dispatch}))(JobItem);

How do I unit test a init() function with Jasmine?

I'm trying to write a unit test for an init function and I'm getting an error where I am calling collectionReport.init() in the test....
TypeError: undefined is not an object
This is the code I am trying to test...
class CollectionsReport {
constructor({ editCollectionsId, hasCollections}) {
this.editCollectionsId = editCollectionsId;
this.hasCollections = hasCollections
}
init({ id, name }) {
this.id = id;
this.name = name;
// need to test this
if (this.hasCollections) {
this.collection = this.collections.find(c => c.staticId === 'CAR-COLLECTION');
}
}
And this is my test so far
describe('CollectionsReport', () => {
const collectionArgs = {
editCollectionsId: jasmine.createSpy(),
hasCollections: false,
};
const collections = [
{
id: 1,
name: 'foo',
staticId: 'CAR-COLLECTIONS',
},
{
id: 2,
name: 'bar',
staticId: 'TRUCK-COLLECTIONS',
},
];
let collectionReport;
beforeEach(() => {
collectionReport = new CollectionsReport(collectionArgs);
});
describe('.init()', () => {
it('should test hasCollections', () => {
collectionReport.init();
//test this.hasCollections here
});
});
});
I'm sure its a mess, so please comment on how to fix and improve it.
Not sure what is the purpose of the CollectionsReport class, but maybe this will lead you to the right direction:
class CollectionsReport {
constructor({ editCollectionsId, hasCollections}) {
this.editCollectionsId = editCollectionsId
this.hasCollections = hasCollections
}
init({ collections, staticId }) {
this.hasCollections = !!collections.find(c => c.staticId === staticId)
}
}
describe('CollectionsReport', () => {
const collectionArgs = {
editCollectionsId: jasmine.createSpy(), // Not really using it
hasCollections: false
}
const collections = [
{
id: 1,
name: 'foo',
staticId: 'CAR-COLLECTIONS'
}, {
id: 2,
name: 'bar',
staticId: 'TRUCK-COLLECTIONS'
}
]
describe('.init()', () => {
let collectionReport
beforeEach(() => {
collectionReport = new CollectionsReport(collectionArgs)
})
it('should test hasCollections', () => {
collectionReport.init({ collections, staticId: 'CAR-COLLECTIONS' })
expect(collectionReport.hasCollections).toBe(true)
})
it('should test hasCollections', () => {
collectionReport.init({ collections, staticId: 'SOMETHING-ELSE' })
expect(collectionReport.hasCollections).toBe(false)
})
})
})

Categories

Resources