Unexpected use of 'event' no-restricted-globals - javascript

I am writing an onChange function in a react app but I am getting an error. here is the function
const handleChange = e => {
// handle Change
setDisabled(event.empty);
setError(event.error ? event.error.message : '');
}
I am getting an error that says:
Unexpected use of 'event' no-restricted-globals
I don't know what the error means.

Here is the corrected version of your code:
const handleChange = e => {
// handle Change
setDisabled(e.empty);
setError(e.error ? e.error.message : '');
}
In this version, we use the e parameter instead of the global event variable.

Related

calling multiple functions in #keydown vue3 error

I have two functions which I'm trying to call with an inside input tag using #keydown="test(); numOnly();"
and get the error TypeError: Cannot read properties of undefined (reading 'key')
numOnly(event) {
const numPattern = /[\d]/;
const eventVal = event.key;
if (!numPattern.test(eventVal)) {
event.preventDefault();
} else {
return true;
}
},
test() {
console.log('Test function() called');
}
When I remove the test() function it works.
The error should be telling you it's occurring on this line:
var eventVal = event.key;
Cannot read properties of undefined (reading 'key') means the object that 'key' is a property of (event) is undefined. If you console.log(event) right before that line, I'm sure you'd get undefined proving the error message correct. event is a parameter of your method, so the only reason it would be undefined is if nothing is being passed in.
Checking the Vue docs, you pass the original DOM event to a method using the special $event variable. Therefore, this should fix your error:
<input #keydown="test(); numOnly($event);" />

cant set a state inside function (react)

Learning by coding, here i have simple graph, where are different datas such as current, all and filtered data, first code works fine, but i wanted to setState so i changed code a little (second code), if i uncomment 'setTest' it give 'Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.' is there a fix to this or should i somehow use useEffect?
and another question is why should i call function 'kk()', and not just reference to it 'kk' because when i use reference it give error 'Uncaught TypeError: Cannot read properties of undefined' but when calling function it wont give error, but then i have used reference to function without problem 'onClickNode={onClickNode}' .
1:
import { Graph } from "react-d3-graph";
<Graph data={
hideData ?
curentData ? allData : filteredData
: allData }
onClickNode={onClickNode}
/>
2:
import { Graph } from "react-d3-graph";
const [test, setTest] = useState<any>("testData1");
const kk = () => {
// setTest("testData2")
return curentData ? allData : filteredData;
};
<Graph
data={hideData ? kk() : allData} onClickNode={onClickNode}
/>
English is not my mother language so could be mistakes.
You should not call a state changing function within your rendering logic without some sort of condition. Without a condition to prevent a state change results in an infinite loop as you are seeing.
One option you can try is call setTest("testData2") on a particular user action, like this:
const [test, setTest] = useState<any>("testData1");
const kk = () => {
return curentData ? allData : filteredData;
};
const onClickNode = () => {
// Handle other click logic...
setTest("testData2");
};
<Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />
But without seeing more of that code, that option may not make sense for you.
Another option would be to check the value of test before calling setTest("testData2"), like this:
const [test, setTest] = useState<any>("testData1");
const kk = () => {
if (test !== "testData2") {
setTest("testData2");
}
return curentData ? allData : filteredData;
};
<Graph data={hideData ? kk() : allData} onClickNode={onClickNode} />

Uncaught TypeError: setting getter-only property "selectedProjectId"

Trying to set this variable to an element's id number, but I can't make sense of this error statement.
{Uncaught TypeError: setting getter-only property "selectedProjectId"}
I declared the variable here.
const LOCAL_STORAGE_LIST_KEY = 'project.lists';
const LOCAL_STORAGE_SELECTED_LIST_ID_KEY = 'project.selectedProjectId';
const projects = JSON.parse(localStorage.getItem(LOCAL_STORAGE_LIST_KEY)) || [];
const selectedProjectId = localStorage.getItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY);
function save() {
localStorage.setItem(LOCAL_STORAGE_LIST_KEY, JSON.stringify(projects));
localStorage.setItem(LOCAL_STORAGE_SELECTED_LIST_ID_KEY, selectedProjectId);
}
export {
projects,
save,
selectedProjectId,
}
I try to assign it a different value here.
projectList.addEventListener('click', e => {
if (e.target.tagName.toLowerCase() === 'li') {
console.log(e.target.dataset.projectId);
console.log('works');
selectedProjectId = e.target.dataset.projectId;
saveAndRender();
}
});
I'm following webdev simplified's tutorial on a better to-do-list in js. I'm following pretty closely, but mine keeps throwing the type error. How do I fix this? Any advice would be helpful. For more clarification, I am also using webpack if that is important.
const cannot be assigned to a new value. Use let instead.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const

Insufficient Jest coverage

I have the below code:
<ReturnToLastSearch
href={'/listings'}
onClick={(e): void => {
e.preventDefault();
router.back();
}}
/>
Inside ReturnToLastSearch({ href, onClick }: Props) has the following:
<a className="button" onClick={!onClick ? urlOnClick : onClick}>
Everything is working fine, except jest complains that my diff, which adds the onClick prop and the ternary has insufficient tests coverage!
I tried:
it('when onClick is defined uses onClick', () => {
const call = ()=> ({back: jest.fn()});
jest.mock('next/router', call)
const { getByText } = render(<ReturnToLastSearch href="foo" onClick={call}/>);
getByText(i18n.t('favorites.returnToLastSearch') as string).click();
expect(router.back).toHaveBeenCalledWith('/listings')
});
I tried the above, which is the same as the version without onClick except for the expect and the mock of router.back(). However, I got an error telling me that the second argument in the jest.mock() should be an inline function.
What sort of test would make sense and also convince jest to leave me alone?
Thank you
I ended-up with:
it('when onClick is defined uses onClick', () => {
const call = jest.fn();
const { getByText } = render(<ReturnToLastSearch href="foo" onClick={call} />);
getByText(i18n.t('favorites.returnToLastSearch') as string).click();
expect(call.mock.calls.length).toBe(1);
});
It is not the most useful test, in my opinion. Yet, it did get jest off my back.

Class level variables Javascript/Angular

I am new to angular I have a class level variable in my angular component called moratoriumID. I call a method which calls a POST and then assigns a number to moratoriumID that is returned from the POST . I believe this works as intended, as I see the number show up in the chrome debugger console . Later on I try to access the variable and use it. It says its undefined. Why ? What am I not understanding ? How can I use the moratoriumID later in code ? Any explanation would be most appreciated. --Jason
export class AddMoratoriumsComponent implements OnInit {
moratoriumID: number;
//this gets called and assigns the moratoriumID from what I see
PostMoratorium(moratoriumtopost: Moratorium):void {
this.moratoriumService.PostMoratorium(moratoriumtopost)
.pipe(takeUntil(this.ngUnsubscribe))
.subscribe((data) => (this.moratoriumID) = (data),
(error) => (console.log(error)),
() => console.log('Post moratorium is complete', this.moratoriumID),
);}
//...I call it
this.PostMoratorium(moratoriumtopost);
//Later I try to use moratoriumID but it says its undefined ...why ?
if (this.selectzipvalues.length>0){
const res = this.isoLocs.filter(i => this.selectzipvalues.includes(i.zipCode));
res.forEach(myFunction);
function myFunction(item) {
const moratoriumlocationstopost = {
county:item.county ,
city:item.city,
zip:item.zipCode,
moratoriumId:this.moratoriumID, //IT SAYS ITS UNDEFINED ..WHY ?
} as MoratoriumLocation;
}}
Answer seems to be be to use switchMap().

Categories