Validation of fetched data from API Redux React - api

So, I will go straight to the point. I am getting such data from api:
[
{
id: 123,
email: asd#asd.com
},
{
id: 456,
email: asdasd.com
},
{
id: 789,
email: asd#asd
},
...
]
and I should validate email and show this all info in a list, something like this:
asd#asd.com - valid
asdasd.com - invalid
asd#asd - invalid
...
My question is what is the best way to store validation data in a store? Is it better to have something like "isValid" property by each email? I mean like this:
store = {
emailsById: [
123: {
value: asd#asd.com,
isValid: true
},
456: {
value: asdasd.com,
isValid: false
},
789: {
value: asd#asd,
isValid: false
}
...
]
}
or something like this:
store = {
emailsById: [
123: {
value: asd#asd.com
},
456: {
value: asdasd.com
},
789: {
value: asd#asd
}
...
],
inValidIds: ['456', '789']
}
which one is better? Or maybe there is some another better way to have such data in store? Have in mind that there can be thousands emails in a list :)
Thanks in advance for the answers ;)

I recommend reading the article "Avoiding Accidental Complexity When Structuring Your App State" by Tal Kol which answers exactly your problem: https://hackernoon.com/avoiding-accidental-complexity-when-structuring-your-app-state-6e6d22ad5e2a
Your example is quite simplistic and everything really depends on your needs but personally I would go with something like this (based on linked article):
var store = {
emailsById: {
123: {
value: '123#example.com',
},
456: {
value: '456#example.com',
},
789: {
value: '789#example.com',
},
// ...
},
validEmailsMap: {
456: true, // true when valid
789: false, // false when invalid
},
};

So your best option would be to create a separate file that will contain all your validations methods. Import that into the component you're using and then when you want to use the logic for valid/invalid.
If its something that you feel you want to put in the store from the beginning and the data will never be in a transient state you could parse your DTO through an array map in your reducer when you get the response from your API.
export default function (state = initialState, action) {
const {type, response} = action
switch (type) {
case DATA_RECIEVED_SUCCESS:
const items = []
for (var i = 0; i < response.emailsById.length; i++) {
var email = response.emailsById[i];
email.isValid = checkEmailValid(email)
items.push(email)
}
return {
...state,
items
}
}
}
However my preference would be to always check at the last moment you need to. It makes it a safer design in case you find you need to change you design in the future. Also separating the validation logic out will make it more testable

First of all, the way you defined an array in javascript is wrong.
What you need is an array of objects like,
emails : [
{
id: '1',
email: 'abc#abc.com',
isValid: true
},
{
id: '2',
email: 'abc.com',
isValid: false;
}
];
if you need do access email based on an id, you can add an id property along with email and isValid. uuid is a good way to go about it.
In conclusion, it depends upon your use case.
I believe, the above example is a good way to keep data in store because it's simple.
What you described in your second example is like maintaining two different states. I would not recommend that.

Related

How to not trigger watch when data is modified on specific cases

I'm having a case where I do wish to trigger the watch event on a vue project I'm having, basically I pull all the data that I need then assign it to a variable called content
content: []
its a array that can have multiple records (each record indentifies a row in the db)
Example:
content: [
{ id: 0, name: "First", data: "{jsondata}" },
{ id: 1, name: "Second", data: "{jsondata}" },
{ id: 2, name: "Third", data: "{jsondata}" },
]
then I have a variable that I set to "select" any of these records:
selectedId
and I have a computed property that gives me the current object:
selectedItem: function () {
var component = this;
if(this.content != null && this.content.length > 0 && this.selectedId!= null){
let item = this.content.find(x => x.id === this.selectedPlotBoardId);
return item;
}
}
using this returned object I'm able to render what I want on the DOM depending on the id I select,then I watch this "content":
watch: {
content: {
handler(n, o) {
if(o.length != 0){
savetodbselectedobject();
}
},
deep: true
}
}
this work excellent when I modify the really deep JSON these records have individually, the problem I have is that I have a different upload methord to for example, update the name of any root record
Example: changing "First" to "1"
this sadly triggers a change on the watcher and I'm generating a extra request that isnt updating anything, is there a way to stop that?
This Page can help you.
you need to a method for disables the watchers within its callback.

How to create getters and setters for all sub-properties of a Vuex state property efficiently?

I couldn't find the answer anywhere.
Let's say we have Vuex store with the following data:
Vuex store
state: {
dialogs: {
dialogName1: {
value: false,
data: {
fileName: '',
isValid: false,
error: '',
... 10 more properties
}
},
dialogName2: {
value: false,
data: {
type: '',
isValid: false,
error: '',
... 10 more properties
}
}
}
}
Dialogs.vue
<div v-if="dialogName1Value">
<input
v-model="dialogName1DataFileName"
:error="dialogName1DataIsValid"
:error-text="dialogName1DataError"
>
<v-btn #click="dialogName1Value = false">
close dialog
</v-btn>
</div>
<!-- the other dialogs here -->
Question
Let's say we need to modify some of these properties in Dialogs.vue.
What's the best practices for creating a getter and setter for every dialog property efficiently, without having to do it all manually like this:
computed: {
dialogName1Value: {
get () {
return this.$store.state.dialogs.dialogName1.value
},
set (value) {
this.$store.commit('SET', { key: 'dialogs.dialogName1.value', value: value })
}
},
dialogName1DataFileName: {
get () {
return this.$store.state.dialogs.dialogName1.data.fileName
},
set (value) {
this.$store.commit('SET', { key: 'dialogs.dialogName1.data.fileName', value: value })
}
},
dialogName1DataIsValid: {
get () {
return this.$store.state.dialogs.dialogName1.data.isValid
},
set (value) {
this.$store.commit('SET', { key: 'dialogs.dialogName1.data.isValid', value: value })
}
},
dialogName1DataIsError: {
get () {
return this.$store.state.dialogs.dialogName1.data.error
},
set (value) {
this.$store.commit('SET', { key: 'dialogs.dialogName1.data.error', value: value })
}
},
... 10 more properties
And this is only 4 properties...
I suppose I could generate those computed properties programmatically in created(), but is that really the proper way to do it?
Are there obvious, commonly known solutions for this issue that I'm not aware of?
getters can be made to take a parameter as an argument - this can be the 'part' of the underlying state you want to return. This is known as Method-style access. For example:
getFilename: (state) => (dialogName) => {
return state.dialogs[dialogName].data.fileName
}
You can then call this getter as:
store.getters.getFilename('dialogName1')
Note that method style access doesn't provide the 'computed property' style caching that you get with property-style access.
For setting those things in only one central function you can use something like this:
<input
:value="dialogName1DataFileName"
#input="update_inputs($event, 'fileName')">
// ...
methods:{
update_inputs($event, whichProperty){
this.$store.commit("SET_PROPERTIES", {newVal: $event.target.value, which:"whichProperty"})
}
}
mutation handler:
// ..
mutations:{
SET_PROPERTIES(state, payload){
state.dialogName1.data[payload.which] = payload.newVal
}
}
Let me explain more what we done above. First we change to v-model type to :value and #input base. Basically you can think, :value is getter and #input is setter for that property. Then we didn't commit in first place, we calling update_inputs function to commit because we should determine which inner property we will commit, so then we did send this data as a method parameter (for example above code is 'fileName') then, we commit this changes with new value of data and info for which property will change. You can make this logic into your whole code blocks and it will solved your problem.
And one more, if you want to learn more about this article will help you more:
https://pekcan.dev/v-model-using-vuex/

How to watch for a value which depends on another value vue?

First off, sorry for the vague title; I couldn't come up with a really succinct one. Here's my situation:
Let's say I have users, topics and comments in a vuex store. Users have names, a list of topics as well as the topic they have currently selected:
users: {
1: {
name: 'Tom',
topics: [1, 2],
selectedTopic: null // set to 1 and then 2 when user clicks "next"
},
2: {... }
},
topics:
1: {
title: 'Post!',
comments: [1, 2],
selectedComment: null
},
2: { ... }
},
comments:
1: {
title: 'Cool!'
},
2: { ... }
}
If a user is selected, I want to show their name. If a user also selects a topic, this topic should be displayed as well; they can also cycle through the topics. For every topic, they can cycle through the comments in the same way. Thus:
computed: {
// some getters
// ...
user () {
return this.getUser(this.userId)
},
topic () {
return this.getTopic(this.user.topics[this.user.selectedTopic])
},
comment () {
return this.getComment(this.topic.comments(this.topic.selectedComment])
}
In this case, the cycling works, but the console shows a TypeError: "this.user.topics is undefined" or "this.user.selectedTopicis undefined" at the start (only sometimes), which is true, of course, since we haven't selected a user yet. On the other hand, if I replace this with
topic () {
if (this.user) return this.getTopic(this.user.topics[this.user.selectedTopic])
}
I don't get any errors, but neither does the value update when the selected topic is changed. Is there a good way to handle the issue?
Based on a comment by Ivo Gelov, I arrived at
return this.getTopic((this.user.topics || {})[this.user.selectedTopic])
This seems to do the trick.

Ember.js - Accessing nested data via serializer

What is the best approach for accessing a single nested record in Ember?
The JSON response which we are trying to manipulate looks gets returned as the following: (the attribute being targeted is the tradeIdentifier property)
trade:
tradeIdentifier:"83f3f561-62af-11e7-958b-028c04d7e8f9"
tradeName:"Plumber"
userEmail:"test#gmail.com"
The project-user model looks partially like:
email: attr('string'),
trade:attr(),
tradeId: attr(),
The project-user serializer looks partially like:
export default UndefinedOmitted.extend(EmbeddedRecordsMixin, {
primaryKey: 'userRoleId',
attrs: {
'email': { key: 'userEmail' },
'trade': { key: 'trade' },
'tradeId': { key: 'tradeIdentifier' },
},
});
The trade attr here is a placeholder to make sure that the data was accessible.
I would like to be able to access the tradeIdentifier without having to do the following in the component:
const trade = get(formRole, 'trade');
if (trade) {
set(formProps, 'tradeId', trade.tradeIdentifier);
}
Have tested creating a trade-id transform (referenced via tradeId: attr('trade-id')), however to no avail.
export default Transform.extend({
deserialize(val) {
const trade = val;
const tradeId = val.tradeIdentifier;
return tradeId;
},
serialize(val) {
return val;
},
});
Can anyone suggest where I'm going wrong?
A transform seems a bit overkill for what I'm trying to achieve here, however it does the job. Managed to get it working by modifying the following:
In serializers/project-user.js:
'tradeId': { key: 'trade' },
Note that this references the property in the payload to transform, not the property being targeted (which was my mistake).
In models/project-user.js:
tradeId: attr('trade-id'),
Attribute references the transform.
In transform/trade-id.js:
export default Transform.extend({
deserialize(val) {
let tradeId = val
if (tradeId) {
tradeId = val.tradeIdentifier;
}
return tradeId;
},
serialize(val) {
return val;
},
});
If there's a simpler solution outside of transforms, I would still be open to suggestions.

Vuelidate empty object on select validation issue

I would like to know how to validate empty object using vuelidate. I tried to give a demonstration on jsfiddle as links follows
Vue.use(window.vuelidate.default)
const { required, minLength } = window.validators
new Vue(
{
el: "#app",
data: {
companies: [
{
id: 1,
name: 'facebook'
},
{
id: 2,
name: 'apple'
}
],
text: {
id: null,
name: null
}
},
validations: {
text: {
required
}
}
}
)
jsfiddle
$v.text is valid because it is a non-empty object. That means it doesn't have 'falsy' value so it meets the requirement. One way to make it work:
validations: {
text: {
id: {required},
name: {required},
},
},
JSFiddle
If you don't want to repeat items object structure, you can write a custom validator.
There is missing information about how to use withParams in the documentation of vuelidate page.
So i have searched on its github page and found this link .
According to link i came up with that solution
import { withParams } from 'vuelidate'
export const checkIfNull = withParams(
{ type: 'required' },
value => (value.id === null ? false : true)
)
There is nothing special about validating an object, you just need to define the structure and add any validation rules you require.
Please see the example I created and take another look at the Collections docs.