I'm working on a note taking app. I would like to show the error message only if there is no search result. The problem is that currently I'm displaying the error message even when I don't have any notes in the array, which is not what I want. What am I doing wrong?
Here's my code and what I've tried so far:
const [notesList, setNotesList] = React.useState<string[]>([]);
const [query, setQuery] = React.useState<string>("");
const addNote = (): void => {
setNotesList([...notesList, ""]);
};
const deleteNote = React.useCallback(
(idx: number): void => {
const newList = [...notesList];
newList.splice(idx, 1);
setNotesList(newList);
},
[notesList]
);
const updateNote = React.useCallback(
(idx: number, text: string): void => {
const newList = [...notesList];
newList.splice(idx, 1, text);
setNotesList(newList);
},
[notesList]
);
React.useEffect(() => {
const storage_string = sessionStorage.getItem(LOCAL_STORAGE_KEY);
if (!storage_string) return;
try {
const savedNotes = JSON.parse(storage_string) as string[];
if (savedNotes) setNotesList(savedNotes);
} catch (err) {
console.log("error");
}
}, []);
React.useEffect(() => {
sessionStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(notesList));
}, [notesList]);
const getFilteredNotes = (notes: string[], query: string) => {
if (!query) {
return notes;
}
return notes.filter((note) => note.includes(query));
};
const filteredNotes = getFilteredNotes(notesList, query);
const updateQuery = (event: React.ChangeEvent<HTMLInputElement>) =>
setQuery(event.target.value);
const handleSearch = debounce(updateQuery, 500);
return (
<div ref={wrapperRef}>
<GlobalStyle />
<SidePanel showSidePanel={showSidePanel}>
<HeaderContainer>
<SearchInput placeholder='Search notes' type='text' onChange={handleSearch} />
<Button variant='icon' onClick={addNote}>
<AddIcon/>
</Button>
</HeaderContainer>
{filteredNotes && filteredNotes.length > 0 ? filteredNotes.map((note: string, idx: number) => (
<Note
onChange={updateNote}
remove={deleteNote}
idx={idx}
text={note}
key={idx}
/>
)) : <Text>No results found</Text>}
</SidePanel>
<ToggleButton variant='primary' onClick={toggleSidePanel}>
<NoteIcon width='2rem' height='2rem'/>
Notes
</ToggleButton>
</div>
);
};
Your condition will only ever render notes, or your fallback text:
{filteredNotes && filteredNotes.length > 0 ? filteredNotes.map((note: string, idx: number) => (
<Note
onChange={updateNote}
remove={deleteNote}
idx={idx}
text={note}
key={idx}
/>
)) : <Text>No results found</Text>}
As #kelly mentioned above, you need to check your notesList and if you don't want to show your fallback text then skip rendering this section.
There's many ways you can do that - abstracting the logic for what to render given different scenarios to a function would be more readable, but you can try this to see if it solves your problem:
{notesList.length > 0 && // <- this is new, and the rest is wrapped in parenthesis ()
(filteredNotes && filteredNotes.length > 0 ? (
filteredNotes.map((note: string, idx: number) => (
<Note
onChange={updateNote}
remove={deleteNote}
idx={idx}
text={note}
key={idx}
/>
))
) : (
<Text>No results found</Text>
))}
If your notesList is empty, it won't render anything
Related
Hello I am stuck in updating the star rating from react js code using axios to mongodb. The stars are getting clicked but the value is not showing neither getting updating.
Here is the front end code:
const StarRating = (props) => {
console.log(props);
return (
<div>
{Array(5)
.fill(0)
.map((_, idx) => (
<label key={idx}>
<input
type="radio"
name="rating"
onChange={handleRate}
value={props.ratingValue}
checked={idx === props.ratingValue}
/>
<FaStar color={idx < 3 ? "#01af93" : "#bbb"} />
</label>
))}
</div>
);
};
const Report = (props) => {
const { advices } = useSelector((state) => state.advice);
const [rate, setRating] = useState(null);
useEffect(() => {
if (!advices) {
dispatch(fetchAdvices(history));
}
});
useEffect(() => {
async function fetchRate() {
try {
const { rating } = await axios.get(http://localhost:8080/rating);
console.log(rating + "user rating");
} catch(error) {
console.log(error);
}
};
fetchRate();
}, []);
const handleRate = async() => {
const rate = await axios.post(http://localhost:8080/rating, {rating:rate, collegeId: collegeId});
props.setRating(rate)
}
return (
<>
<Container>
<Grid>
<Fragment>
<Grid >
<Card>
<CardContent><> <div>{advices[0}.college_name}
<StarRating setRating={(val) => setRate(val)} ratingValue={rate} />
</div></></CardContent>
</Card>
</Grid>
</>
)};
How to update values of rating based on collegeID from react code. The concept here is to update the value of rating based on the college name showed to user from the score he gets. College name is getting displayed but the value of rating is not getting displayed nor getting changed.
Code seems messed up during copy/paste, is this what you are trying to achive?
const StarRating = (props) => {
console.log(props)
// sends rating to database then updates the rating ui
const handleRate = async (ratingToSave) => {
const rate = await axios.post('http://localhost:8080/rating', {
rating: ratingToSave,
// collegeId should come from wherever stored
collegeId: collegeId
})
props.setRating(rate)
}
return (
<div>
{Array(5)
.fill(0)
.map((_, idx) => (
<label key={idx}>
<input
type="radio"
name="rating"
// idx+1 if minimum rating is 1
onChange={() => handleRate(idx + 1)}
value={props.ratingValue}
checked={idx === props.ratingValue}
/>
<FaStar color={idx < 3 ? '#01af93' : '#bbb'} />
</label>
))}
</div>
)
}
const Report = (props) => {
const { advices } = useSelector((state) => state.advice)
const [rate, setRate] = useState(null)
useEffect(() => {
if (!advices) {
dispatch(fetchAdvices(history))
}
// dependency array might need update, test first
}, [advices])
useEffect(() => {
async function fetchRate() {
try {
const { rating } = await axios.get('http://localhost:8080/rating')
console.log(rating + 'user rating')
} catch (error) {
console.log(error)
}
}
fetchRate()
// to rerender and refetch after user sends rating to database
}, [rate])
// jsx implement again
return (
<>
<StarRating setRating={(val) => setRate(val)} ratingValue={rate} />
</>
)
}
Im a newbie in React and Im creating a simple form that sends data to DB. I made it work almost as I wanted, the only problem is that I dont know how to update the state which has an array inside.
The idea is to make a form so I can add recipes which include the whole recipe data that I map through to render each recipe. In the data object I need simple strings most of the time but then I need also three arrays or objects, I prefer the arrays in this case.
I found many solutions for class components but still I could figure out how to update the arrays. I even figured out how to update one array from a string input separated only with commas, then .split(', ') and .trim() and map() through but I could not setFormFields({}) at two places at the same time since the createRecipe() is async. The split just did not happen before the array was sent to the DB as a string. Thats why I dont put the whole code here.
I will simplify the code to make you see clear.
const defaultFormFields = {
title: '',
imageUrl: '',
leadText: '',
};
const NewRecipeForm = () => {
const [formFields, setFormFields] = useState(defaultFormFields);
const { title, imageUrl, leadText } = formFields;
const [ingredients, setIngredients] = useState([])
const handleFormFieldsChange = (event) => {
setFormFields({ ...formFields, [event.target.name]: event.target.value })
}
const handleIngredientsChange = ( event) => {
**// here I need help**
setIngredients()
}
const addIngredient = () => {
setIngredients([...ingredients, ''])
}
const removeIngredient = (index) => {
**// here I need help**
}
const createRecipe = async (event) => {
event.preventDefault()
// addRecipe sends the object to Firestore DB
addRecipe('recipes', url, formFields)
resetFormFields()
}
const resetFormFields = () => {
setFormFields(defaultFormFields);
};
return (
<NewRecipeFormContainer>
<h1>New recipe</h1>
<form onSubmit={createRecipe}>
<h1>Title</h1>
<input label='Title' placeholder='Recipe title' name='title' value={title} onChange={handleChange} />
<input label='imageUrl' placeholder='imageUrl' name='imageUrl' value={imageUrl} onChange={handleFormFieldsChange} />
<input label='leadText' placeholder='leadText' name='leadText' value={leadText} onChange={handleFormFieldsChange} />
<h1>Ingredients</h1>
**// here I need help ?**
{
ingredients.map((ingredient, index) => {
return (
<div key={index}>
<input label='Ingredience' placeholder='Ingredience' name='ingredient' value={ingredient.ingredient} onChange={handleChange} />
**// here I need help ?**
<button onClick={removeIngredient} >remove</button>
</div>
)
})
}
<button onClick={addIngredient} >add</button>
</form>
<Button onClick={createRecipe}>ODESLAT</Button>
</NewRecipeFormContainer>
)
}
I will appreciate any hint or help. Ive been totally stuck for two days. Thank you!
Here's an example of how to update a single element in a list.
const updateSingleItemInList = (index, update) => {
setList(list.map((l, i) => i === index ? update : l));
};
const add = (element) => setList([...list, element]);
Try simplifying your state first:
const [ingredients, setIngredients] = useState([]);
const [tips, setTips] = useState([]);
Then it becomes simple to write the handlers:
const updateIngredient = (index, text) => {
setIngredients(list.map((ing, i) => i === index ? text : ing));
};
const addIngredient = () => setIngredients([...ingredients, ""]);
Then you can create the form object when the user wants to submit:
addRecipe('recipes', url, {
ingredients: ingredients.map(i => ({ingredients: i})),
// etc.
});
Put it all together and here is the minimum viable example of a component that manages a dynamic number of form elements (tested, works):
export const TextBody = () => {
const [list, setList] = useState([{ name: "anything" }]);
const add = () => setList(l => [...l, { name: "" }]);
const remove = i => setList(l => [...l.slice(0, i), ...l.slice(i + 1)]);
const update = (i, text) => setList(l => l.map((ll, ii) => (ii === i ? { name: text } : ll)));
return (
<>
<TouchableOpacity onPress={add}>
<Text text="add" />
</TouchableOpacity>
{list.map((l, i) => (
<>
<Text text={JSON.stringify(l)} />
<TouchableOpacity onPress={() => remove(i)}>
<Text text="remove" />
</TouchableOpacity>
<Input onChange={c => update(i, c.nativeEvent.text)} />
</>
))}
</>
);
};
You can return those CRUD functions and the state from a custom hook so you only have to write this once in a codebase.
Edit: Just for fun, here's the same component with a reusable hook:
const useListOfObjects = (emptyObject = {}, initialState = []) => {
const [list, setList] = useState(initialState);
const add = () => setList(l => [...l, emptyObject]);
const remove = i => setList(l => [...l.slice(0, i), ...l.slice(i + 1)]);
const update = (i, text, field) =>
setList(l => l.map((ll, ii) => (ii === i ? { ...ll, [field]: text } : ll)));
return {
list,
add,
remove,
update,
};
};
export const TextBody = () => {
const { list, add, remove, update } = useListOfObjects({ name: "", id: Math.random() });
return (
<>
<TouchableOpacity onPress={add}>
<TextBlockWithShowMore text="add" />
</TouchableOpacity>
{list.map((l, i) => (
<React.Fragment key={`${l.id}`}>
<TextBlockWithShowMore text={JSON.stringify(l)} />
<TouchableOpacity onPress={() => remove(i)}>
<TextBlockWithShowMore text="remove" />
</TouchableOpacity>
<Input onChange={c => update(i, c.nativeEvent.text, "name")} />
</React.Fragment>
))}
</>
);
};
I encountered this error while writing this code. I thought since I am using map on array, this error occurred. so I tried to put 'key' there but couldn't find how to make it work.
If I remove that line and try console.log(posts) then I can see my posts list on console. Could anyone help me out here?
Thanks in advance!
export const list = async ctx => {
// query는 문자열이기 때문에 숫자로 변환해 주어야 함
// 값이 주어지지 않았다면 1을 기본으로 사용
const page = parseInt(ctx.query.page || '1', 10);
if (page < 1) {
ctx.status = 400;
return;
}
const { tag, username } = ctx.query;
// tag, username 값이 유효하면 객체 안에 넣고, 그렇지 않으면 넣지 않음
const query = {
...(username ? {'user.username': username} : {}),
...(tag ? { tags:tag } : {}),
};
try {
const posts = await Post.find(query)
.sort({_id: -1})
.limit(10)
.skip((page-1)*10)
.exec();
const postCount = await Post.countDocuments(query).exec();
ctx.set('Last-Page', Math.ceil(postCount / 10));
ctx.body = posts.map(post => ({
...post,
body: removeHtmlAndShorten(post.body),
}));
} catch (e) {
ctx.throw(500, e);
}
};
and below code is what it's rendering!
const PostItem = ({ post }) => {
const { publishedDate, user, tags, title, body, _id } = post;
return (
<PostItemBlock>
<h2>
<Link to={`/#${user.username}/${_id}`}>{title}</Link>
</h2>
<SubInfo username={user.username} publishedDate={new Date(publishedDate)} />
<Tags tags={tags} />
<p>{body}</p>
</PostItemBlock>
)
}
const PostList = ({ posts, loading, error, showWriteButton }) => {
// 에러 발생 시
// if (error) {
// return <PostListBlock>Error occured</PostListBlock>
// }
return (
<PostListBlock>
<WritePostButtonWrapper>
{showWriteButton && (
<Button cyan to="/write">
New post
</Button>
)}
</WritePostButtonWrapper>
{/* 로딩중이 아니고 포스트 배열이 존재할 때만 보여줌 */}
{!loading && posts && (
<div>
{posts.map(post => (
<PostItem post={post} key={post._id} />
))}
</div>
)}
</PostListBlock>
)
}
export default PostList;
try this :
<div>
{posts.map((post,index)=> (
<PostItem post={post} key={index} />
))}
</div>
so weirdly I solved this issue myself and I used this code below.
I used round bracket on 'post' while using map and it successfully brought data. Hope it can help someone who has similar issue with me XD
const postCount = await Post.countDocuments(query).exec();
ctx.set('Last-Page', Math.ceil(postCount / 10));
ctx.body = posts.map((post) => ({
...post,
body: removeHtmlAndShorten(post.body),
}));
} catch (e) {
ctx.throw(500, e);
}
};
Still with my react project, now I'm learning the hooks, perhaps I have an issue with the 'infinite loop' (Maximum update depth exceeded) and I can't figure out how to handle this. I have redux to handle the states. I used useEffect, because when I clicked on a div, it was showing, or did what I wanted, always one step late
function OffersWhatTypeOfWebsiteComponent(props) {
const dispatch = useDispatch()
const [active, setActive] = useState(1)
const [typeWebSite, setTypeWebSite] = useState('withCMS')
const updateTypeWebSite = () => {
dispatch({
type: "TYPE_WEBSITE",
payload: typeWebSite
})
}
useEffect(() => {
updateTypeWebSite();
}, [updateTypeWebSite()]);
const renderElements = (props) => {
switch (active) {
case 1 :
return (
<>
<OffersChooseYourPackageCMSComponent
/>
</>
);
break
case 2 :
return (
<>
<OffersChooseYourPackageLikeAProComponent/>
</>
)
default:
return 'error'
}
}
return (
<div>
<OffersTitleCardComponent
titleNumber='2'
titleSection='What type of Website'
/>
<div className='chooseYourProject'>
<OffersCardsWithCheckComponent
titleCard='With CMS'
subtitleCard='xxxx'
active={active === 1 ? 'listing-active' : 'listing'}
onClick={() => {
setActive(1);
setTypeWebSite('withCMS');
updateTypeWebSite()
}}
/>
<OffersCardsWithCheckComponent
titleCard='Like a pro'
subtitleCard='xxx'
active={active === 2 ? 'listing-active' : 'listing'}
onClick={() => {
setActive(2);
setTypeWebSite('like a pro');
updateTypeWebSite()
}}
/>
</div>
{
renderElements({})
}
</div>
);
}
export default OffersWhatTypeOfWebsiteComponent;
This is the sub-component :
function OffersChooseYourPackageCMSComponent(props) {
const dispatch = useDispatch()
const [active, setActive] = useState(1)
const [packageWebSite, setPackageWebSite] = useState('Shopify')
const [pricePackageWebSite, setPricePackageWebSite] = useState(300)
const updatePackageWebSite = () => {
dispatch({
type: "PACKAGE_WEBSITE",
payload: {packageWebSite, pricePackageWebSite}
})
}
useEffect(() => {
updatePackageWebSite();
}, [updatePackageWebSite()]);
const renderElements = () => {
switch (active) {
case 1 :
return (
<>
<OffersNumbersOfProductsComponent/>
</>
);
break
case 2 :
return (
<>
<OffersNumbersOfPagesComponent/>
<OffersWoocommerceComponent/>
</>
);
break
default :
return 'error'
}
}
return (
<div>
<OffersTitleCardComponent
titleNumber='3'
titleSection='Choose your package'
/>
<div className="shopify">
<OffersCardsWithCheckComponent
onClick={() => {
setActive(1);
setPackageWebSite('Shopify');
setPricePackageWebSite(300);
updatePackageWebSite()
}}
active={active === 1 ? "listing-active" : "listing"}
titleCard='Shopify'
subtitleCard='xxx'
pricePackage='$54349'
detailPrice='(1 landing page + up to 5 products)'
/>
<OffersCardsWithCheckComponent
onClick={() => {
setActive(2);
setPackageWebSite('WordPress');
setPricePackageWebSite(900);
updatePackageWebSite()
}}
active={active === 2 ? "listing-active" : "listing"}
titleCard='WordPress'
subtitleCard='xxxx'
pricePackage='$23349'
detailPrice='(1 landing page)'
/>
</div>
{renderElements()}
</div>
);
}
export default OffersChooseYourPackageCMSComponent;
Don't hesitate to tell me some good practices too, on what I should arrange also if needed.
Thanks for your help
You should replicate this into your sub-component as well
const updateTypeWebSite = useCallback(() => {
dispatch({
type: "TYPE_WEBSITE",
payload: typeWebSite
})
}, [typeWebSite])
useEffect(() => updateTypeWebSite(), [updateTypeWebSite]);
Read this at reactjs documentation
Found something that worked, don't know if it's the best solutuion :
const [typeWebSite, setTypeWebSite] = useState('withCMS')
const updateTypeWebSite = () => {
dispatch({
type: "TYPE_WEBSITE",
payload: typeWebSite
})
}
useEffect(() => {
updateTypeWebSite()
},[typeWebSite,setTypeWebSite]);
I've created a form and am saving the data to a json file locally. I can save all the data except for the questions with multiple selections and multiple checkboxes. It only saves the last one selected. I am trying to write a switch statement within a React Hook that is working to help save the submitted form. I keep getting an error "cannot identify type of undefined." I'm new to react and don't know what to do from here.
This is in my hooks folder:
export const useInputChange = (customValue, callback) => {
const [value, setValue] = useState(customValue ? customValue : "" || []);
const handleChange = (event) => {
var newValue;
switch (customValue.type) {
case "multipleSelection":
newValue = $("multipleSelection").find("option:checked");
break;
case "checkboxChoice":
newValue = $("checkboxChoice").find("input:checked");
break;
default:
newValue = event.target.value;
}
setValue(newValue);
if (callback) {
callback(event.target.name, newValue);
}
};
return {
value: value,
handleChange: handleChange
};
};
This is my callback in my components folder:
const callback = (name, value) => {
console.log("callback", name, value);
inlineData[name] = value;
setInlineData(inlineData);
console.log(inlineData);
};
The jquery works in the console to pull up the correct arrays.
This is the component:
export const Survey = (props) => {
const [page, setPage] = useState(1);
const [isFinalPage, setIsFinalPage] = useState(false);
const [surveyValues, setSurveyValues] = useState({});
const [loadedInputs, setLoadedInputs] = useState({});
const [question, setQuestion] = useState({});
const [inlineData, setInlineData] = useState({});
const { surveyId } = props;
const triggerBackendUpdate = () => {
console.log(question);
console.log(surveyValues);
setPage(1);
setSurveyValues({});
setQuestion({});
};
useEffect(() => {
if (surveyId) {
const inputDataFile = import(`./data_${surveyId}.json`);
inputDataFile.then((response) => {
setLoadedInputs(response.default);
});
}
});
const handleSubmit = (event) => {
event.preventDefault();
event.persist();
for (let formInput of event.target.elements) {
const isText = isTextInput(formInput.type);
console.log(formInput);
if (isText) {
surveyValues[formInput.name] = formInput.value;
question[formInput.question] = formInput.question;
}
if (formInput.type === "selectMultiple") {
let selected = [].filter.call(
formInput.options,
(option) => option.selected
);
console.log(formInput);
console.log(selected);
console.log(formInput.options.selected);
const values = selected.map((option) => option.value);
surveyValues[formInput.name] = values;
question[formInput.name] = formInput.question;
}
if (formInput.type === "checkbox") {
surveyValues[formInput.name] = formInput.value;
question[formInput.name] = formInput.question;
}
}
setQuestion(question);
setSurveyValues(surveyValues);
const nextPage = page + 1;
const inputs = props.inputs
? props.inputs.filter((inputOption) => inputOption.page ===
nextPage): [];
if (isFinalPage) {
triggerBackendUpdate();
} else {
if (inputs.length === 0) {
setIsFinalPage(true);
} else {
setPage(nextPage);
}
}
};
const callback = (name, value) => {
console.log("callback", name, value);
inlineData[name] = value;
setInlineData(inlineData);
console.log(inlineData);
};
const saveSurvey = async () => {
await fetch("/api/survey", {
method: "POST",
body: JSON.stringify(inlineData),
headers: {
"Content-Type": "application/json",
},
}).catch((error) => {
console.error(error);
});
};
const inputs = props.inputs
? props.inputs.filter((inputOption) => inputOption.page === page)
: [];
return (
<form onSubmit={handleSubmit}>
{isFinalPage !== true &&
inputs.map((obj, index) => {
let inputKey = `input-${index}-${page}`;
return obj.type === "radio" || obj.type === "checkbox" ? (
<SurveyRadioInput
object={obj}
type={obj.type}
required={props.required}
triggerCallback={callback}
question={obj.question}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "checkbox" ? (
<SurveyCheckboxInput
object={obj}
type={obj.type}
required={props.required}
triggerCallback={callback}
question={obj.question}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "select" ? (
<SurveySelectInput
className="form-control mb-3 mt-3"
object={obj}
type={obj.type}
question={obj.question}
required={props.required}
triggerCallback={callback}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : obj.type === "selectMultiple" ? (
<SurveySelectMultipleInput
className="form-control mb-3 mt-3"
object={obj}
type={obj.type}
question={obj.question}
required={props.required}
triggerCallback={callback}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
) : (
<SurveyTextInput
className="mb-3 mt-3 form-control"
object={obj}
type={obj.type}
question={props.question}
required={props.required}
triggerCallback={callback}
placeholder={obj.placeholder}
defaultValue={obj.defaultValue}
name={obj.name}
key={inputKey}
/>
);
})}
{isFinalPage !== true ? (
<button name="continue-btn" className="btn btn-primary my-5 mx-5">
Continue
</button>
) : (
<Link to="/thankyou">
<button
onClick={saveSurvey}
type="button"
className="btn btn-primary my-5 mx-5"
>
Submit Survey
</button>
</Link>
)}
</form>
);
};
This is in my inputs folder:
export const SurveySelectMultipleInput = (props) => {
const { object } = props;
const { value, handleChange } = useInputChange(
props.defaultValue,
props.triggerCallback
);
const inputType = isTextInput(props.type) ? props.type : "";
const inputProps = {
className: props.className ? props.className : "form-control",
onChange: handleChange,
value: value,
required: props.required,
question: props.question,
type: inputType,
name: props.name ? props.name : `${inputType}_${props.key}`,
};
console.log(value);
return (
<>
<div id={object.name}>
<h5>{props.question}</h5>
<select
{...inputProps}
name={object.name}
className={props.className}
multiple={object.multiple}
>
<option hidden value>
Select one
</option>
{object.options.map((data, index) => {
return (
<option
value={data.value}
id={`${object.name}-${index}`}
key={`${object.type}-${index}`}
className={`form-check ${props.optionClassName}`}
>
{data.label}
</option>
);
})}
</select>
</div>
</>
);
};
It's hard to tell exactly how your components and hooks behave without having an example showing their behavior and properties. Regardless, I made some assumptions and tried to answer:
First of all, what is the expected type of customValue in useInputChange? Are you expecting a string or an array? Then what is the type attribute on it that you're checking in your switch statement?
As for the jquery selector, what is multipleSelection? Is it the class name you're using for your select elements? Then your selector must start with a dot a/nd then you can get the value by calling .val method on the selected element:
newValue = $(".multipleSelection").val();
Here's a working example for multiple select elements, using your code: https://codepen.io/kaveh/pen/QWNNQMV
Note that I had to assign an arbitrary type attribute to VALUE to get it working with your switch statement.
All that being said, as I mentioned in my comment, it's recommended to use ref to access elements created by React and not other query selectors such as those you get from jquery.
https://reactjs.org/docs/refs-and-the-dom.html
https://reactjs.org/docs/hooks-reference.html#useref