What I'm trying to do is to not allow the user to add two same languages. The user has the possibility to click the button, that generates the input fields, and puts the language.
export default class AddLanguage extends React.Component {
constructor(props) {
super(props);
this.state = {
language: [],
};
}
handleClick() {
var language = this.state.language;
this.setState({
language: language,
});
}
handleLanguageChanged(i, event) {
var language= this.state.language;
language[i] = event.target.value;
this.setState({
language: language,
});
sessionStorage.setItem('items', JSON.stringify({language}));
}
handleLanguageDeleted(i) {
var language= this.state.language;
language.splice(i, 1);
this.setState({
language: language,
});
}
componentDidMount() {
this.userItems = JSON.parse(sessionStorage.getItem('items'));
if (sessionStorage.getItem('items')){
this.setState({
items: this.userItems.items,
})
}else {
this.setState({
items: [],
})
}
}
renderRows() {
var context = this;
How to not allow the user to not add the same language?
CodePudding user response:
Assuming the new language entered by the user is processed using handleLanguageChanged
and that it is added/updated at index i
(with value being sourced from event.target.value
) the below may be helpful to achieve the desired objective:
handleLanguageChanged(i, event) {
// hold the event.target.value for future reference
const updLang = event.target.value;
// use setState with a function
this.setState(prev => {
const currList = prev.language;
// check if currList has updLang except at location "i"
const isDupe = currList.some(
(lang, idx) => (idx !== i && lang.toLowerCase() === updLang)
);
// if it is dupe, simply return "prev" (no actual update)
if (isDupe) return prev;
else {
// update the currList & use it to set the new state
currList[i] = updLang;
return {...prev, language: currList};
}
});
};
Also, kindly reconsider if the below function is necessary as-is:
handleClick() {
var language = this.state.language;
this.setState({
language: language,
});
}