Side-effects-in-computed-properties - vue.js

I want to avoid having side effects in my code, but I don't know how to fix these, does some one can help?
computed: {
sumarVerduras(){
this.totalVerduras = 0;
for( const verdura of this.verduras){
this.totalVerduras = this.totalVerduras + verdura.cantidad
} return this.totalVerduras;
}
}
It work as I want but side effect is there
Module Warning (from ./node_modules/eslint-loader/index.js):
error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:53:7:
51 | computed: {
52 | sumarVerduras(){
53 | this.totalVerduras = 0;
| ^
54 | for( const verdura of this.verduras){
55 | this.totalVerduras = this.totalVerduras + verdura.cantidad
56 | } return this.totalVerduras;
error: Unexpected side effect in "sumarVerduras" computed property (vue/no-side-effects-in-computed-properties) at src\App.vue:55:11:
53 | this.totalVerduras = 0;
54 | for( const verdura of this.verduras){
55 | this.totalVerduras = this.totalVerduras + verdura.cantidad
| ^
56 | } return this.totalVerduras;
57 | }
58 | }

You should not edit any Vue component's data in computed property. Here you modify this.totalVerduras, which is considered as Vue's component data.
You can change to:
computed: {
sumarVerduras() {
let totalVerduras = 0;
for (const verdura of this.verduras) {
totalVerduras = totalVerduras + verdura.cantidad
}
return totalVerduras;
}
}

You can do this as well:
computed: {
sumarVerduras() {
return verduras.reduce((a, x) => a + x.cantidad, 0);
}
}
This method gets rid of totalVerduras variable and the for loop.

Related

animated flatlist with animated ref typescript error

Why I get this ts error ?
(property) ref: React.RefObject<FlatList<any>>
Type '{ ref: RefObject<FlatList<any>>; data: IInstructionsData[]; renderItem: ListRenderItem<IInstructionsData>; ... 6 more ...; showsHorizontalScrollIndicator: false; }' is not assignable to type 'IntrinsicAttributes & { ItemSeparatorComponent?: ComponentType<any> | AnimatedNode<ComponentType<any> | null | undefined> | null | undefined; ... 146 more ...; simultaneousHandlers?: Ref<...> | ... 2 more ... | undefined; } & { ...; } & { ...; }'.
Property 'ref' does not exist on type 'IntrinsicAttributes & { ItemSeparatorComponent?: ComponentType<any> | AnimatedNode<ComponentType<any> | null | undefined> | null | undefined; ... 146 more ...; simultaneousHandlers?: Ref<...> | ... 2 more ... | undefined; } & { ...; } & { ...; }'.ts(2322)
Code:
import Animated, { useAnimatedScrollHandler, useSharedValue, useDerivedValue, useAnimatedRef } from 'react-native-reanimated';
const AnimatedFlatlist = (Animated.createAnimatedComponent(
FlatList
) as unknown) as <T>(props: RNGHFlatListProps<T>) => React.ReactElement;
<AnimatedFlatlist
ref={flatlistRef}
data={mockData}
renderItem={renderItem}
onScroll={handleScroll}
keyExtractor={(item, i) => i.toString()}
initialNumToRender={2}
keyboardShouldPersistTaps='handled'
horizontal
pagingEnabled
showsHorizontalScrollIndicator={false}
/>
the error comes at AnimatedFlatlist on ref
what I am doing wrong and how can I solve this issue ?
Your code snippet is incomplete. Where did you define the ref for the AnimatedFlatList?
It should look something like this:
const flatListRef = useRef<FlatList<T>>(null);

Assert Dynamic Classes Tescafe and vue-virtual-scroll-list

Case:
New to testcafe and I would appreciate if someone could help.
I want to loop through a list of buttons with dynamic classes, click them and check if the class has changed.
I fail to loop and assert that the classes has changed.
(The element that matches the specified selector is not visible.)
fixture`The Loop`.beforeEach(async (t) => {
await t.useRole(loginUser);
})
test("Summary List check marks", async (t) => {
// const markStop = Selector('div.btn-group-y').find('[data-attribute="markStopBtn"]')
await t.click(selector.driverReadyBtn);
let markStopBtn = await selector.markStopBtn
let markStopBtnCount = await markStopBtn.count;
for(let i=0; i < markStopBtnCount; i++){
if(markStopBtn.nth(i).exists && markStopBtn.nth(i).visible) {
await t
.click(markStopBtn.nth(i))
// .expect(markStopBtn.withAttribute('class', 'btn-primary').exists).ok()
}
}
});
File.Vue///
<div
data-attribute="markStopBtn"
:class="[
'btn btn-icon btn-secondary-outline p-4',
{
['btn-primary']: completed,
['btn-cancelled']: issued,
['btn-blueDark-inverse']: !issued && !completed,
},
]"
#click="clickCompleteStop"
>
Trows Error
(The element that matches the specified selector is not visible.)
| if(markStopBtn.nth(i).exists && markStopBtn.nth(i).visible) {
23 | await t
> 24 | .click(markStopBtn.nth(i))
25 | // .expect(markStopBtn.withAttribute('class', 'btn-primary').exists).ok()
26 | }

Store object in array in react-native using async-storage

I have generated random Qr code using Guid id and I'm saving lasted generated Qr code to async-storage but how do i store every generated random Guid id to async-storage in term of array.
here is the code to generate random id.
let base64Logo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAA..";
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
AsyncStorage.setItem("id", uuidv4());
console.log(uuidv4());
Thank you!
Convert your array to a string using JSON.stringify on save and back to an array using JSON.parse on read
let base64Logo = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAOEAA..";
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
// save item in array
try {
const myArrayString = await AsyncStorage.getItem('ids');
const myArray = myArrayString !== null?JSON.parse(myArray):[];
myArray.push(uuidv4())
await AsyncStorage.setItem('ids', JSON.stringify(myArray));
} catch (error) {
// Error saving data
}
// when you want to retrieve array
try {
const myArray = await AsyncStorage.getItem('ids');
if (myArray !== null) {
// We have data!!
console.log(JSON.parse(myArray));
}
} catch (error) {
// Error retrieving data
}

How to stub/mock a return value with Sinon.js (vue) to test my method

I tried so many code but no one worked In my case.
// returns all groups from DB
getAllGroups() {
apiService.getAllGroups().then((data) => {
this.groups = data;
})
.catch((error) => {
console.log(error.response.data.message);
});
},
How can I fake a value for data to test the method getAllGroups?
Here is the unit test solution, you can use jest.mock() or jest.spyOn() to mock or spy on the apiService.getAllGroups method.
group.js:
import apiService from './apiservice';
class Group {
groups = [];
getAllGroups() {
return apiService
.getAllGroups()
.then((data) => {
this.groups = data;
})
.catch((error) => {
console.log(error.response.data.message);
});
}
}
export default Group;
apiservice.js:
const apiService = {
async getAllGroups() {
return [];
},
};
export default apiService;
group.test.js:
import Group from './group';
import apiService from './apiservice';
describe('59591410', () => {
afterEach(() => {
jest.restoreAllMocks();
});
it('should get all groups correctly', async () => {
jest.spyOn(apiService, 'getAllGroups').mockResolvedValueOnce([1, 2]);
const group = new Group();
await group.getAllGroups();
expect(group.groups).toEqual([1, 2]);
});
it('should handle error', async () => {
const error = { response: { data: { message: 'some error' } } };
jest.spyOn(apiService, 'getAllGroups').mockRejectedValueOnce(error);
jest.spyOn(console, 'log');
const group = new Group();
await group.getAllGroups();
expect(console.log).toBeCalledWith('some error');
});
});
Unit test result with coverage report:
PASS src/stackoverflow/59591410/group.test.js
59591410
✓ should get all groups correctly (10ms)
✓ should handle error (6ms)
console.log node_modules/jest-mock/build/index.js:860
some error
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 92.31 | 100 | 80 | 91.67 | |
apiservice.js | 66.67 | 100 | 0 | 66.67 | 3 |
group.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 6.114s, estimated 12s
Source code: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/59591410

How to return nested JSON?

I have 3 table in PostgreSQL database.
QUESTIONS table:
| id (int) | text (text) |
|----------|--------------------------------------|
| 1 | What is your favorite color? |
| 2 | What is your favorite football club? |
OPTIONS table:
| id (int) | text (text) |
|----------|-------------|
| 1 | red |
| 2 | blue |
| 3 | grey |
| 4 | green |
| 5 | brown |
QUESTIONS_OPTIONS table:
| question_id (int) | option_id (int) |
|-------------------|-----------------|
| 1 | 1 |
| 1 | 2 |
| 1 | 3 |
| 1 | 4 |
| 1 | 5 |
In Golang application I create such models:
type Option struct {
ID int `json:"option_id"`
Text string `json:"option_text"`
}
type Question struct {
ID int `json:"question_id"`
Text string `json:"question_text"`
Options []Option `json:"options"`
}
In controller I have such code:
var GetQuestions = func(responseWriter http.ResponseWriter, request *http.Request) {
rows, _ := database.DBSQL.Query("SELECT * FROM questions;")
defer rows.Close()
var questions []Question
for rows.Next() {
var question Question
var options []Option
queries, _ := database.DBSQL.Query(`select options.id as option_id, options.text as option_text from questions_options inner join questions on questions_options.question_id = ` + &question.ID + ` inner join options on questions_options.option_id = options.id`)
queries.Close()
for queries.Next() {
var option Option
if err := queries.Scan(&option.ID, &option.Text); err != nil {
log.Println(err)
}
options = append(options, option)
}
if err := rows.Scan(&question.ID, &question.Text, options); err != nil { // service raise error in this line: sql: expected 2 destination arguments in Scan, not 3
log.Println(err)
}
questions = append(questions, question)
}
utils.Response(responseWriter, http.StatusOK, questions)
}
When I try to make GET request to take all questions with all there options service such incorrect result:
[
{
"question_id": 0,
"question_text": "",
"options": null
},
{
"question_id": 0,
"question_text": "",
"options": null
}
]
Where I make mistake?
You should move queries.Close() to the end of loop, like this:
var GetQuestions = func(responseWriter http.ResponseWriter, request *http.Request) {
rows, _ := database.DBSQL.Query("SELECT * FROM questions;")
defer rows.Close()
var questions []Question
for rows.Next() {
var question Question
if err := rows.Scan(&question.ID, &question.Text); err != nil {
log.Println(err)
continue
}
queries, _ := database.DBSQL.Query(`select options.id as option_id, options.text as option_text from questions_options inner join questions on questions_options.question_id = $1 inner join options on questions_options.option_id = options.id`, question.ID)
for queries.Next() {
var option Option
if err := queries.Scan(&option.ID, &option.Text); err != nil {
log.Println(err)
}
question.Options = append(question.Options, option)
}
queries.Close()
questions = append(questions, question)
}
utils.Response(responseWriter, http.StatusOK, questions)
}