Enter event not working with react typescript - typescript-typings

code: setPack(target.value) not working on enter key. but on change works. any one help me ?
<input value={pack} onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => {
const target = e.currentTarget as HTMLInputElement;
if (e.key === 'Enter') {
setPack(target.value);//no woking
}
}} onChange={e => setPack(e.target.value)} />
<button onClick={updatePack}>Update</button>

I updated with setPack(e.currentTarget.value); it works fine for me.

Related

Search Data not working Angular NodeJS API

i am created the search part using angular and node js. i have tested through the postman it is working fine. when connect with frond end anqular application is it not working error displayed
Failed to load resource: the server responded with a status of 404 (Not Found)
what i tried so far i attached below please check.
i tried on the url http://localhost:9001/user/findOne?first_name=kobinath
this is working well on postman but tested through the anqular didn't work. i attached the code what i tried so far.
employee.component.ts
search()
{
let name= {
"first_name" : this.first_name
};
this.http.post("http://localhost:9001/user/findOne",name).subscribe((resultData: any)=>
{
console.log(resultData);
});
}
employee.component.html
<form>
<div class="form-group">
<label>First Name</label>
<input type="text" [(ngModel)]="first_name" [ngModelOptions]="{standalone: true}" class="form-control" id="name" placeholder="Enter Name">
</div>
<button type="submit" class="btn btn-primary mt-4" (click)="search()" >Search</button>
</form>
</div>
What I noticed: With Postman you send first_name as a query parameter, but in your Angular-code you attach it to the request-body.
To achieve the equivalent of what you do in Postman, you could use the following code:
search(firstName: string) {
const params = new HttpParams().set('first_name', firstName);
const body = {
first_name : firstName
};
this.http.post("http://localhost:9001/user/findOne", body, { params: params })
.subscribe((resultData: any)=>
{
console.log(resultData);
});
}
Btw: Why don't you use GET instead of POST?

Queshtion about removing an item for a map

Im having trouble configuring a remove function for my shopping-list project, the purpose of the project is to make a shopping list with a checkbox, a quantity and an item name, but there's another feature that i can't figure out how to add it, i want to a button
( ), that will remove the selected item, now, the item are mapped, which means they are in lines, if i write ("milk", "2") and then ("milk","3"), it will go line after line, like this:
milk - 2
milk - 3.
now, i want to add a delete button, next to every line that is created, that will be able to delete that line which is connected to him, im guessing i need to define an index, and the map function will do it for me, and it will be easier, but i havent found any explanation about it, so, if you can add to the code a remove button, and explain how did u do it, that would be lovely, thanks in advance guys!
import React, { useState } from 'react';
export const ShoppingListPageContainer = () => {
const [item, setItem] = useState('');
const [quantity, setQuantity] = useState('');
const [list, setList] = useState([]);
const add = () => {
const date = { item, quantity };
if (item || quantity) {
setList((ls) => [...ls, date]);
setItem('');
setQuantity('');
}
};
return (
<div>
<label>
<input
name='item'
value={item}
onChange={(e) => setItem(e.target.value)}
/>
<input
type='number'
name='quantity'
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/>
<button onClick={add}>add</button>
</label>
{list.map((a) => {
return (
<div>
<il>{a.item}</il>
<il>{' - ' + a.quantity + ' '}</il>
<input type='checkbox' />
<button />
</div>
);
})}
</div>
);
};
Steps:
create function which will accept id as parameter and delete the item in list which matches that id. (Note: id should be uniq).
For example:
const deleteItem = (id) => {
//logic delete by id from list
}
Add this button on map and bind id.
For example:
list.map((a)=><div>
<il>{a.item}</il>
<il>{" - "+ a.quantity + " "}</il>
<button onClick={deleteItem.bind(this, a.id)} />
</div>)
By this way you can delete only one item at a time.
By binding ID to function you will call function with binded id only.
I hope this will help you to progress... Best of luck!
export const ShoppingListPageContainer = () => {
const [item, setItem] = useState("");
const [quantity, setQuantity] = useState("");
const [list, setList] = useState([]);
const handleAddItem = () => {
const date = { item, quantity };
if (item || quantity) {
const newList = [...list, date]
setList(newList);
setItem("");
setQuantity("");
}
};
const handleRemoveItem = (index)=>{
const newList = list.filter((item)=>list.indexOf(item) !==index)
setList(newList)
}
return (
<div>
<label>
<input
name="item"
value={item}
onChange={(e) => setItem(e.target.value)}
/>
<input
type="number"
name="quantity"
value={quantity}
onChange={(e) => setQuantity(e.target.value)}
/>
<button onClick={handleAddItem}>add</button>
</label>
{list.map((a,i) => (
<div>
<il>{a.item}</il>
<il>{` ${a.quantity} `}</il>
<input type="checkbox" />
<button onClick={()=>{handleRemoveItem(i)}} />
</div>
))}
</div>
);
};
This may help you however if it does not please check the implementation of the filter method
https://www.w3schools.com/jsref/jsref_filter.asp

How Can I Test an MUI ToggleButtonGroup with a userEvent?

I am using MUI ToggleButtonGroup component like so:
<ToggleButtonGroup
color="primary"
value={mode}
exclusive
onChange={changeHandler}
fullWidth
className="mt-4"
>
<ToggleButton value="login">Login</ToggleButton>
<ToggleButton value="register">Register</ToggleButton>
</ToggleButtonGroup>
When clicking the 'Register' button, it works fine in the UI. I'd like to get a proper test written with React Testing Library.
Here's what I have:
setup();
heading = screen.getByRole("heading", { level: 2 });
const registerButton = screen.getByRole("button", { name: /register/i });
userEvent.click(registerButton);
expect(heading).toHaveTextContent("Register");
The crux of the issue seems to be that userEvent.click somehow doesn't call the changeHandler. Is there some type of bubbling or something that I need to concern myself with?
Here's a prettyDOM log of the relevant components:
<button
aria-pressed="false"
class="MuiButtonBase-root MuiToggleButton-root MuiToggleButton-fullWidth MuiToggleButton-sizeMedium MuiToggleButton-primary MuiToggleButtonGroup-grouped MuiToggleButtonGroup-groupedHorizontal css-j4p6el-MuiButtonBase-root-MuiToggleButton-root"
tabindex="0"
type="button"
value="register"
>
Register
<span
class="MuiTouchRipple-root css-8je8zh-MuiTouchRipple-root"
/>
</button> <h2
class="MuiTypography-root MuiTypography-h5 css-ag7rrr-MuiTypography-root"
>
Login
</h2>
Add an id to the component:
<ToggleButton id={${data.value}}> {data.label}
test case:
describe("ToggleButtonGroupComponent onChange Testing", () => {
const onChange = vi.fn();
it("toggle group change value and new value updated and last value no more checked", () => {
const { container } = render(<ToggleButtonGroupComponent {...props} onChange={onChange} />);
// Before change selection
const allValueToggleButton = QueryAttributeById(container, "ssh") as HTMLInputElement;
expect(allValueToggleButton.value).toEqual("ssh");
// Change selection
const withValueToggleButton = QueryAttributeById(container, "http") as HTMLInputElement;
fireEvent.click(withValueToggleButton);
expect(withValueToggleButton.value).toEqual("http");
// Old value is no more checked
expect(allValueToggleButton.value).toEqual("ssh");
});
});

Use mapping function to render buttons and how can each button works independently in React js

I have 3 sets of button here, I want to disable 'cancel button' after clicking once, and vice versa.
However when I disable the 'cancel' button from first set, the 'cancel' button from other sets will be disabled too.
In this case I want to disable the 'cancel' button from first set only.
How do I solve this issue or is there any approach to do so.
any help and suggestions will be appreciated
note ** I am using Mapping function to render the buttons
my client side:
function App() {
const [taskNumber, setTaskNumber] = useState('')
const [disable, setDisable] = useState(true)
const onChange = (e) => {
setTaskNumber(e.target.value)
}
const onClick = () => {
console.log('world')
setDisable(!disable)
}
const button = (index) => {
return (
< div >
<button onClick={() => onClick()} disabled={!disable}>hello</button>
<button onClick={() => onClick()} disabled={disable}>cancel</button>
</div >
)
}
let items = []
for (let i = 0; i < taskNumber; i++) {
// items.push(button(i))
items.push(i)
}
<Form>
<Form.Group as={Col}>
<Form.Label>Number of Task</Form.Label>
<Form.Control
type="number"
min='1'
placeholder="Enter number of task"
name='taskNumber'
value={taskNumber}
onChange={onChange}
/>
</Form.Group>
</Form>
{items.map((number) => {
return button(number)
})}
My React user Interface
You were close, you can use an array in disable to control which element is enabled.
*** edit ***
I didn't have access to the form components you were using so I just made a more basic example for you to refer to. See my codesandbox:
https://codesandbox.io/s/prod-fast-0zneb?file=/src/App.js

State is not upating in renderer() component

I'm very new to react JS, and I am using it to build a app now. I have a question.
In of of the Button Click event i have a code logic like this:
handlestartbutton(event) {
const accesskey = localStorage.getItem(localStorageKeys.accessTokenKey);
const decodedAccessKey = jwt_decode(accesskey);
const date = dateConverter.epochToReadableDate(decodedAccessKey.exp);
if (date.currentTime < date.expiryDate) {
this.setState({
accesstokenexpirydate: true
}, () => {
if(this.state.accesstokenexpirydate === false) {
//rest of the code
}
})
In renderer() i have a a pop up UI like this:
renderer()
{
{this.state.accesstokenexpirydate === true ? (
<Popup
open ={this.state.open}
closeOnDocumentClick={false}
closeOnEscape={false}
onClose={this.closeModal}className
>
<div className={popstyles.popupBody}>
<div className={popstyles.modalClose}>
<a className="close" onClick={this.closeModal}>
×
</a>
{""}
<div className ={popstyles.unAutherizedUser}>
<label >{homeConstantMessages.accessTokenExpire}</label>
<div className ={popstyles.unAutherizedUserMsg}>
<label>{homeConstantMessages.accessTokenExpireMsg}</label>
<button className ={styles.refreshaccessbtn} onClick = {this.navigateToHomePage.bind(this)} label = {homeConstantMessages.refreshbtn}>
</button>
</div>
</div>
</div>
</div>
</Popup>
) : (
''
)}
}
The problem is when the first time start button is clicked this pop up UI is not getting popped even though the state variable accesstokenexpirydate is set to true. when second time the button is cicked UI is popping up. can anyone please help me out here
1) I think you have to apply arrow function like follows and then you can use this
handlestartbutton=(event)=> {...}
2) I'm quite confused about the name, don't you think it should be render(...) instead of renderer()

Resources