So I'm using the Creatable component of the react-select library. I want to be able to add the created option into my options array on keyDown. How it looks right now
My states:
const [value, setValue] = useState([]);
const [inputValue, setInputValue] = useState('');
const [selectedValues, setselectedValues] = useState([]);
const [current, setCurrent] = useState([]);
const [selection, setSelection] = useState(statusOptions);
My functions
const handleInputChange = (value) => {
setInputValue(value);
};
const handleOnChange = (haha) => {
setCurrent(haha);
};
const handleKeyDown = () => {
setTimeout(() => {
setNewValues();
}, [2700]);
};
const setNewValues = (event) => {
const newOption = { label: inputValue, inputValue };
inputValue !== '' && setSelection([...selection, newOption]);
setCurrent(current);
let difference = current.filter((x) => !value.includes(x));
setInputValue('');
setselectedValues(difference);
};
How the component looks
<CreatableSelect
options={selection}
isMulti
onChange={handleOnChange}
onInputChange={handleInputChange}
inputValue={inputValue}
value={selectedValues.selected}
inputValue={inputValue}
onKeyDown={handleKeyDown}
/>
The problem: Right now, the inputValue is added to the dropdown list as the user types and i don't know why. I am able to add and delete the tags on keyDown. But when the user types slow or doesn't write quick enough, the dropdown list ends up with two created options.
So I was way over-complicating this. And thanks to the answer above, i was able to approach it better. I needed to be able to add the tags via keyboard, have them be added into the dropdown list, and then be able to get deleted. Here's the full answer
const [inputValue, setInputValue] = useState('');
const [selectedValues, setselectedValues] = useState({ selected: [] });
const [selection, setSelection] = useState(statusOptions);
const handleInputChange = (value) => {
setInputValue(value);
};
const handleOnChange = () => {
const newOption = { label: inputValue, inputValue };
inputValue !== '' && setSelection([...selection, newOption]);
setInputValue('');
setselectedValues(selection);
};
return (
<div>
<CreatableSelect
options={selection}
isMulti
onChange={handleOnChange}
onInputChange={handleInputChange}
inputValue={inputValue}
value={selectedValues.selected}
inputValue={inputValue}
controlShouldRenderValue={true}
/>
</div>
The option is getting added to the list because setNewValues is being called after the 2700 ms timer expires which is adding a new option item to the menu.
In order to achieve the behavior that you want, remove the onKeyDown function. This will allow you to enter tags without having them populate the menu.
Adding custom tag
Result of creating tag
Related
I did search for those related issues and found some solutions, but most about the lodash debounce. In my case, I create useDebounce as a custom hook and return the value directly.
My current issue is useCallback works with an old debounced value.
Here are my code snips.
//To makes sure that the code is only triggered once per user input and send the request then.
export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timeout = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timeout);
}, [value, delay]);
return debouncedValue;
};
useDebounce works as expected
export const ShopQuantityCounter = ({ id, qty }) => {
const [value, setValue] = useState(qty);
const debounceInput = useDebounce(value, 300);
const dispatch = useDispatch();
const handleOnInputChange = useCallback((e) => {
setValue(e.target.value);
console.info('Inside OnChange: debounceInput', debounceInput);
// dispatch(updateCartItem({ id: id, quantity: debounceInput }));
},[debounceInput]);
console.info('Outside OnChange: debounceInput', debounceInput);
// To fixed issue that useState set method not reflecting change immediately
useEffect(() => {
setValue(qty);
}, [qty]);
return (
<div className="core-cart__quantity">
<input
className="core-cart__quantity--total"
type="number"
step="1"
min="1"
title="Qty"
value={value}
pattern="^[0-9]*[1-9][0-9]*$"
onChange={handleOnInputChange}
/>
</div>
);
};
export default ShopQuantityCounter;
Here are screenshots with console.info to explain what the issue is.
Current quantity
Updated with onChange
I do appreciate it if you have any solution to fix it, and also welcome to put forward any code that needs updates.
This might help you achieve what you want. You can create a reusable debounce function with the callback like below.
export const useDebounce = (value, delay) => {
const [debouncedValue, setDebouncedValue] = useState(value);
let timeout;
const setDebounce = (newValue) => {
clearTimeout(timeout);
timeout = setTimeout(() => setDebouncedValue(newValue), delay);
};
return [debouncedValue, setDebounce];
};
And use the function on your code like this.
export const ShopQuantityCounter = ({ id, qty }) => {
const [value, setValue] = useState(qty);
const [debounceInput, setDebounceInput] = useDebounce(value, 300);
const dispatch = useDispatch();
const handleOnInputChange = useCallback((e) => {
setDebounceInput(e.target.value);
console.info('Inside OnChange: debounceInput', debounceInput);
// dispatch(updateCartItem({ id: id, quantity: debounceInput }));
},[debounceInput]);
console.info('Outside OnChange: debounceInput', debounceInput);
// To fixed issue that useState set method not reflecting change immediately
useEffect(() => {
setValue(qty);
}, [qty]);
return (
<div className="core-cart__quantity">
<input
className="core-cart__quantity--total"
type="number"
step="1"
min="1"
title="Qty"
value={value}
pattern="^[0-9]*[1-9][0-9]*$"
onChange={handleOnInputChange}
/>
</div>
);
};
export default ShopQuantityCounter;
What I would like to happen is when displayBtn() is clicked for the items in localStorage to display.
In useEffect() there is localStorage.setItem("localValue", JSON.stringify(myLeads)) MyLeads is an array which holds leads const const [myLeads, setMyLeads] = useState([]); myLeads state is changed when the saveBtn() is clicked setMyLeads((prev) => [...prev, leadValue.inputVal]);
In DevTools > Applications, localStorage is being updated but when the page is refreshed localStorage is empty []. How do you make localStorage persist state after refresh? I came across this article and have applied the logic but it hasn't solved the issue. I know it is something I have done incorrectly.
import List from './components/List'
import { SaveBtn } from './components/Buttons';
function App() {
const [myLeads, setMyLeads] = useState([]);
const [leadValue, setLeadValue] = useState({
inputVal: "",
});
const [display, setDisplay] = useState(false);
const handleChange = (event) => {
const { name, value } = event.target;
setLeadValue((prev) => {
return {
...prev,
[name]: value,
};
});
};
const localStoredValue = JSON.parse(localStorage.getItem("localValue")) ;
const [localItems] = useState(localStoredValue || []);
useEffect(() => {
localStorage.setItem("localValue", JSON.stringify(myLeads));
}, [myLeads]);
const saveBtn = () => {
setMyLeads((prev) => [...prev, leadValue.inputVal]);
// setLocalItems((prevItems) => [...prevItems, leadValue.inputVal]);
setDisplay(false);
};
const displayBtn = () => {
setDisplay(true);
};
const displayLocalItems = localItems.map((item) => {
return <List key={item} val={item} />;
});
return (
<main>
<input
name="inputVal"
value={leadValue.inputVal}
type="text"
onChange={handleChange}
required
/>
<SaveBtn saveBtn={saveBtn} />
<button onClick={displayBtn}>Display Leads</button>
{display && <ul>{displayLocalItems}</ul>}
</main>
);
}
export default App;```
You've fallen into a classic React Hooks trap - because using useState() is so easy, you're actually overusing it.
If localStorage is your storage mechanism, then you don't need useState() for that AT ALL. You'll end up having a fight at some point between your two sources about what is "the right state".
All you need for your use-case is something to hold the text that feeds your controlled input component (I've called it leadText), and something to hold your display boolean:
const [leadText, setLeadText] = useState('')
const [display, setDisplay] = useState(false)
const localStoredValues = JSON.parse(window.localStorage.getItem('localValue') || '[]')
const handleChange = (event) => {
const { name, value } = event.target
setLeadText(value)
}
const saveBtn = () => {
const updatedArray = [...localStoredValues, leadText]
localStorage.setItem('localValue', JSON.stringify(updatedArray))
setDisplay(false)
}
const displayBtn = () => {
setDisplay(true)
}
const displayLocalItems = localStoredValues.map((item) => {
return <li key={item}>{item}</li>
})
return (
<main>
<input name="inputVal" value={leadText} type="text" onChange={handleChange} required />
<button onClick={saveBtn}> Save </button>
<button onClick={displayBtn}>Display Leads</button>
{display && <ul>{displayLocalItems}</ul>}
</main>
)
I need to use an input filter in React. I have a list of activities and need to filter them like filters on the picture. If the icons are unchecked, actions with these types of activities should not be showed. It works.
The problem that when I use input filter and write letters it works. But when I delete letter by letter nothing changes.
I understand that the problem is that I write the result in the state. And the state is changed.But how to rewrite it correctly.
const [activities, setActivities] = useState(allActivities);
const [value, setValue] = useState(1);
const [checked, setChecked] = useState<string[]>([]);
const switchType = (event: React.ChangeEvent<HTMLInputElement>)=> {
const currentIndex = checked.indexOf(event.target.value);
const newChecked = [...checked];
if (currentIndex === -1) {
newChecked.push(event.target.value);
} else {
newChecked.splice(currentIndex, 1);
}
//function that shows activities if they are checked or unchecked
setChecked(newChecked);
const res = allActivities.filter(({ type }) => !newChecked.includes(type));
setActivities(res);
};
//shows input filter
const inputSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
const foundItems = activities.filter(
(item) => item.activity.indexOf(event.target.value) > -1
);
setActivities(foundItems);
};
//shows participants filter
const countSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue(Number(event.target.value));
const participantsSearch = allActivities.filter(
(item) => item.participants >= event.target.value
);
setActivities(participantsSearch);
};
This is render part
<Input
onChange={inputSearch}
startAdornment={
<InputAdornment position="start">
<SearchIcon />
</InputAdornment>
}
/>
<Input
onChange={countSearch}
type="number"
value={props.value}
startAdornment={
<InputAdornment
position="start"
className={classes.participantsTextField}
>
<PersonIcon />
</InputAdornment>
}
/>
The issue here is that you save over the state that you are filtering, so each time a filter is applied the data can only decrease in size or remain the same. It can never reset back to the full, unfiltered data.
Also with the way you've written the checkbox and input callbacks you can't easily mix the two.
Since the filtered data is essentially "derived" state from the allActivities prop, and the value and checked state, it really shouldn't also be stored in state. You can filter allActivities inline when rendering.
const [value, setValue] = useState<sting>('');
const [checked, setChecked] = useState<string[]>([]);
const switchType = (event: React.ChangeEvent<HTMLInputElement>)=> {
const currentIndex = checked.indexOf(event.target.value);
if (currentIndex === -1) {
setChecked(checked => [...checked, event.target.value]);
} else {
setChecked(checked => checked.filter((el, i) => i !== currentIndex);
}
};
const inputSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
setValue(event.target.value.toLowerCase());
};
...
return (
...
{allActivites.filter(({ activity, type }) => {
if (activity || type) {
if (type) {
return checked.includes(type);
}
if (activity) {
return activity.toLowerCase().includes(value);
}
}
return true; // return all
})
.map(.....
The problem lies with your inputSearch code.
Each time you do setActivities(foundItems); you narrow down the state of your activities list. So when you start deleting, you don't see any change because you removed the rest of the activities from the state.
You'll want to take out allActivities into a const, and always filter allActivities in inputSearch, like so:
const allActivities = ['aero', 'aeroba', 'aerona', 'aeronau'];
const [activities, setActivities] = useState(allActivities);
// ...rest of your code
const inputSearch = (event: React.ChangeEvent<HTMLInputElement>) => {
const foundItems = allActivities.filter(
(item) => item.activity.indexOf(event.target.value) > -1
);
setActivities(foundItems);
};
// ...rest of your code
The ReactSelect component in my app is clearing what I have typed after I make a selection. I don't want it to do that.
I want it to leave it as is. When the user has not entered anything, I want it to show the Placeholder text.
I'm using this component as a search box. Selecting an item from the list accomplishes the task. There's no reason to set the component's value to the selection.
react-select does not support autocompletion out of the box so it requires a bit of extra work and hacks to get what you want.
First off, you need to control the inputValue state, some operations like menu-close or set-value will clear the input afterward.
const [input, setInput] = React.useState("");
const handleInputChange = (e, meta) => {
if (meta.action === "input-change") {
setInput(e);
}
};
return (
<Select
value={selected}
onChange={handleChange}
inputValue={input}
isSearchable
{...}
/>
);
react-select also hides the input after an option is selected so you also need to override that behavior as well.
const [selected, setSelected] = React.useState([]);
const handleChange = (s) => {
setSelected({ ...s });
};
React.useLayoutEffect(() => {
const inputEl = document.getElementById("myInput");
if (!inputEl) return;
// prevent input from being hidden after selecting
inputEl.style.opacity = "1";
}, [selected]);
return (
<Select
value={selected}
inputId="myInput"
onChange={handleChange}
{...}
/>
);
Last but not least, you may want to update your input accordingly after a successful selection, here is a basic example, the code below will append the new option value to your current input after a selection.
Also make sure to override the default filterOption to only taking into account the last word when filtering or nothing will match with the options after the first few words.
const [selected, setSelected] = React.useState([]);
const [input, setInput] = React.useState("");
const handleChange = (s) => {
setSelected({ ...s });
setInput((input) => removeLastWord(input) + s.value);
};
const customFilter = () => {
return (config, rawInput) => {
const filter = createFilter(null);
return filter(config, getLastWord(rawInput));
};
};
return (
<Select
value={selected}
filterOption={customFilter()}
onChange={handleChange}
inputValue={input}
components={{
SingleValue: () => null
}}
{...}
/>
);
Where removeLastWord and getLastWord are just some utility functions.
function getLastWord(str: string) {
return str.split(" ").slice(-1).pop();
}
function removeLastWord(str: string) {
var lastWhiteSpaceIndex = str.lastIndexOf(" ");
return str.substring(0, lastWhiteSpaceIndex + 1);
}
Here is a complete example after combining all of the above.
import React from "react";
import Select, { components, createFilter } from "react-select";
import options from "./options";
function getLastWord(str: string) {
return str.split(" ").slice(-1).pop();
}
function removeLastWord(str: string) {
var lastWhiteSpaceIndex = str.lastIndexOf(" ");
return str.substring(0, lastWhiteSpaceIndex + 1);
}
export default function MySelect() {
const [selected, setSelected] = React.useState([]);
const [input, setInput] = React.useState("");
const handleChange = (s) => {
setSelected({ ...s });
setInput((input) => removeLastWord(input) + s.value);
};
const handleInputChange = (e, meta) => {
if (meta.action === "input-change") {
setInput(e);
}
};
React.useLayoutEffect(() => {
const inputEl = document.getElementById("myInput");
if (!inputEl) return;
// prevent input from being hidden after selecting
inputEl.style.opacity = "1";
}, [selected]);
const customFilter = () => {
return (config, rawInput) => {
const filter = createFilter(null);
return filter(config, getLastWord(rawInput));
};
};
return (
<Select
value={selected}
filterOption={customFilter()}
inputId="myInput"
onChange={handleChange}
blurInputOnSelect={false}
inputValue={input}
onInputChange={handleInputChange}
options={options}
isSearchable
hideSelectedOptions={false}
components={{
SingleValue: () => null
}}
/>
);
}
Live Example
You can also override the input styles using the styles props. There is a whole discussion about this issue on this thread
{
input: (provided) => ({
...provided,
input: {
opacity: "1 !important",
},
}),
}
I'm pretty new to using hooks and functional components.
I have a Filtered List. When I try to update the filter, it will use the last filter state instead of the new one. I must be missing some render/state change orders, but I can't seem to figure out what it is.
I appreciate any help I can get :)
Pseudo code below:
export default function TransferList(props) {
const [wholeList, setWholeList] = React.useState([]);
const [filteredList, setFilteredList] = React.useState([]);
const [filter, setFilter] = React.useState([]);
return (
<>
<TextField
value={filter}
onChange={(e) => {
// Set filter input
setFilter(e.target.value);
// Filter the list
let filtered = wholeList.filter(
(item) => item.indexOf(filter) !== -1
);
setFilteredList(filtered);
}}
/>
<List>
{filteredList.map((item) => (
<ListItem>Item: {item}</ListItem>
))}
</List>
</>
);
}
Inside onChange you should use save the value in a constant, filter will not update just after setFilter(filterValue) as this is an async operation.
<TextField
value={filter}
onChange={e => {
const filterValue = e.target.value;
// Set filter input
setFilter(filterValue);
// Filter the list
let filtered = wholeList.filter(item => item.indexOf(filterValue) !== -1);
setFilteredList(filtered);
}}
/>;
State updates are asynchronous and hence the filter state update doesn't reflect immediately afterwords
You must store the new filter values and set the states based on that
export default function TransferList(props) {
const [wholeList, setWholeList] = React.useState([]);
const [filteredList, setFilteredList] = React.useState([]);
const [filter, setFilter] = React.useState([]);
return (
<>
<TextField value={filter} onChange={(e) => {
// Set filter input
const newFilter = e.target.value;
setFilter(newFilter)
// Filter the list
let filtered = wholeList.filter(item => item.indexOf(newFilter) !== -1)
setFilteredList(filtered)
}} />
<List>
{filteredList.map(item => <ListItem>Item: {item}</ListItem>)}
</List>
</>
)
}
So it turns out I had to give the initial filtered list the entire unfiltered list first. For some reason that fixes it.
const [filteredList, setFilteredList] = React.useState(props.wholeList);
I initially wanted an empty filter to display nothing, but I may have to settle for showing the entire list when the filter is empty
Order your code to be increase readability
In clean code
Main changes:
Use destructuring instead of props
Out the jsx from the html return to increase readability
Use includes instead of indexOf
Add key to the list
export default function TransferList({ wholeList }) {
const [filteredList, setFilteredList] = React.useState(wholeList);
const [filter, setFilter] = React.useState([]);
const handleOnChange = ({ target }) => {
setFilter(target.value);
const updatedFilteredList = wholeList.filter(item => item.includes(target.value));
setFilteredList(updatedFilteredList);
}
const list = filteredList.map(item => {
return <ListItem key={item}>Item: {item}</ListItem>
});
return (
<>
<TextField value={filter} onChange={handleOnChange} />
<List>{list}</List>
</>
);
}
and I have a filter component the do the filter list inside.
import React, { useState } from 'react';
function FilterInput({ list = [], filterKeys = [], placeholder = 'Search',
onFilter }) {
const [filterValue, setFilterValue] = useState('');
const updateFilterValue = ev => {
setFilterValue(ev.target.value);
const value = ev.target.value.toLowerCase();
if (!value) onFilter(list);
else {
const filteredList = list.filter(item => filterKeys.some(key => item[key].toLowerCase().includes(value)));
onFilter(filteredList);
}
}
return (
<input className="filter-input" type="text" placeholder={placeholder}
value={filterValue} onChange={updateFilterValue} />
);
}
export default FilterInput;
the call from the father component look like this
<FilterInput list={countries} filterKeys={['name']} placeholder="Search Country"
onFilter={filterCountries} />
this is in my corona app.. you can look on my Github.
and see how I build the filter
(https://github.com/omergal99/hello-corona)