In my application, in React i have next situation:
I have input where i add different values when i click on save. The value from input is converted from string to array.
So, first time i added a text, i clicked save, and i have 1 value in array.
Second time, i add another text, i click, on save and the first value is changed by second.
I store value in this state:
const [value, setValue] = useState([here comes my value]);
I want to concat the value one after one and i did:
useEffect(()=> {
setAllValues([...value, value])
}, [value])
..but this does't work. How to store all values in one array?
Use the functional form of setState:
setAllValues(prevValue => [...prevValue, newValue])
To perform that operation you would need two states
// one state for array
const [valueArray, setValueArray] = useState([here comes my value]);
// and another state for string
const [value, setValue] = useState('');
// then onSave function
const onSave = () => {
setValueArray([ ...valueArray, value ]);
setValue('');
}
Related
I have a textarea array with values that can be updated. The text values in the array are updated when text is entered into the textarea. The array can also be updated externally.
The problem is that Textarea doesn't want to update its values with setState() like regular text does.
export function GameActions({}) {
const [array, setArray] = useState<Type>([]);
const changeText = (id: number, text: any) => {
actions[id].text = text;
setActions(actions);
};
return {actions.map((action, index) => (<Textarea
defaultValue={action.text}
onChange={(e) =>
changeText(index, e.currentTarget.value)
}
/>))};
};
Provided actions is an array state property, it should be:
setActions((actions)=>{
return actions.map((act,i)=>{
if(i == id) {
act.text = text;
}
return act;
});
});
When a state property is updated using its previous value, the callback argument should be used.
Also, to update an element of a state array, map should be used, rather than the indexation operator [].
Please read this article, to learn how to update state arrays.
I'm trying to add a list inside a state using the set method, but my state remains empty
App.js
// Starts the screts word game
const startGame = () => {
// pick word and pick category
const { word, category } = pickWordAndCategory();
// create array of letters
let wordLetters = word.split("");
wordLetters = wordLetters.map((l) => l.toLowerCase());
// Fill states
setPickedCategory(category);
setPickedWord(word);
setLettersList(wordLetters);
console.log('wordLetters', wordLetters);
console.log('lettersList', lettersList);
setGameState(stages[1].name);
};
const pickWordAndCategory = () => {
// pick a random category
const categories = Object.keys(words);
const category = categories[Math.floor(Math.random() * Object.keys(categories).length)];
console.log('category', category);
// pick a random word
const word = words[category][Math.floor(Math.random() * words[category].length)]
console.log(word);
return { word, category };
}
Here is the browser log
When looking at the log we find our state empty
When you use setLettersList(...), you are not actually changing lettersList variable itself. Notice how when you declare it, const [lettersList, setLettersList] = useState([]); letterList is actually constant, so that variable can't even be changed. Instead, it tells React to rerun the function component, this time giving lettersList the new value. Therefore, for the updated value, it will only come once const [lettersList, setLettersList] = useState([]); is rerun again from the entire function being rerun again.
If you want to monitor changes to lettersList, you can do:
useEffect(() => {
console.log(lettersList);
}, [lettersList]);
This will print lettersList every time it is updated.
States updates are asynchronous, so when you set a new state value and console.log() right after it, it's going to show the previous value, because the state hasn't been updated yet.
That's why your lettersList value show the old value of the state in the console (empty array).
I have two buttons, the movies and tvshows button. When I click on either I change the option to the opposite one as shown on the handleMovieClick and handleTVShowsClick methods. Movies and TVshows may have the same id, that is why the option is important for fetching.
I am printing to the console.
(1) array of movie/tv ids
(2) the option selected
(3) each individual object fetched based on the id and option
When I use the value to calculate the array of movie ids available the first time, I first get an empty array and then the expected result. That is the array of movie ids, option is movie and each individual promise objects is fulfilled.
Here's the kicker, when I click on the tvshows button, I am getting the following two things consoled.
(1) same movie array of ids not updated, option changes to tv, however I get a bunch of promises with "status_message: "The resource you requested could not be found" because I am basically trying to retrieve promises with movie ids, but tvshow option.
Then,
(2) Then the result is changed and I everything as expected. That is option stays the same, changed in above step, the array gets updated, and the individual promise objects are all fulfilled.
What is happening?
I get that it is happening because of the code in my JSX where I am making use of the array ids. I think I need to only call the array.map() part after the useEffect has run and the so array is updated but how to do this and why is useEffect not running the first time?
Here is the code.
const Results = () => {
const options = ['movie', 'tv'];
const { value } = useParams(); // from router
const [ page, setPage ] = useState(1);
const [ option, setOption ] = useState(options[0]);
const [ array, setArray ] = useState([]);
const handleMovieClick = () => {setOption('movie')}
const handleTVShowClick = () => {setOption('tv')}
useEffect(() => {
console.log('HERE');
fetchArrayByPage(value, page, option).then(res => setArray(res));
}, [value, page, option])
console.log(array);
console.log(option);
return (
<div className="results-container">
<div>
<ul className='categories'>
<button onClick={handleMovieClick}>Movies<span>{0}</span></button>
<button onClick={handleTVShowClick}>TV Shows<span>{0}</span></button>
</ul>
</div>
{
<div>
<div className='results-list'>
{array.map((arr, index) => {
console.log(fetchID(arr, option));
return <Card key={index} id={arr} option={option}></Card>})}
</div>
<div className='pages'>
</div>
</div>
}
</div>
);
}
useEffect's callback is fired after the render and fetchArrayByPage seems to be async. So clicking on "TV shows" results in:
option is changed to "tv" (array stays the same)
console.log(array); console.log(option);
render with new option and old array
console.log('HERE'); fetchArrayByPage(...)
some time passes
setArray(res)
render with new option and new array
You should call fetchArrayByPage from your handle*Click handlers:
const handleTVShowClick = () => {
fetchArrayByPage(value, page, "tv").then(res => {
setOption('tv');
setArray(res);
});
}
I am trying to change the state by selecting and deselecting the language option in the code below. So far I can update the state by adding a language, my problem is that, if I click on the same language again, I will add it another time to the array. Can anyone explain me how to add or remove the language from the array when clicked one more time?
export default function Dashboard(props) {
const [language, setLanguage] = useState('');
const handleLanguageChange = changeEvent => {
changeEvent.persist()
setLanguage(prevState => [...prevState, changeEvent.target.value])
};
}
It looks like your only issue is your logic in the place where you are handling update. Usage of hooks is correct
So first of all you need to set proper initial value. As you plan to store your languages in an array.
Second part is updating the array. So you can either find clicked language in the array and if it is exist - then use filter to set your new value or filter and compare length of existing array and new one.
const [language, setLanguage] = useState([]);
const handleLanguageChange = changeEvent => {
changeEvent.persist()
setLanguage(prevState => {
const lang = changeEvent.target.value;
if (prevState.includes(lang) {
return prevState.filter(el => el !== lang);
}
return [...prevState, lang]
})
};
You will need a good old check.
if (!languages.includes(changeEvent.target.value) {
// code to add the language
}
Check the selected value using find() method on language array if it returns undefined, then push into array. Rename the state variable as languages otherwise it's confusing (Naming convention standard).
const [languages, setLanguages] = useState('');
const handleLanguageChange = changeEvent => {
changeEvent.persist()
if (!languages.find(value => value == changeEvent.target.value)) {
setLanguages(prevState => [...prevState, changeEvent.target.value])
}
};
2 Things here
Instead of having
<option value="Deutsch">Deutsch</option>
<option value="Englisch">Englisch</option>
use an languages array of json so it bacomes easy for you to add them like
languages= [{value='Deutsch',name= 'Deutsch',...}]
2.setLanguage sa a direct value
setLanguage(changeEvent.target.value)
My structure:
index.js
--> Filters
--> {list}
Filters contains multiple input elements that set the state in index.js via props.
list displays as you guessed it, a list of elements. I now want to filter this list based on the values returned by the filters. Pretty standard I think and found on millions of sites.
The issue is that I want to make the input onChange function reusable. With only one input in the Filters component I had this (shortened):
<input
value={this.state.anySearch}
onChange={this.handleChange}
/>
handleChange = event => {
const value = event.target.value;
this.setState({ anySearch: value });
};
With multiple inputs I tried this, aka reusable for any input:
handleChange = name => event => {
const value = event.target.value;
this.setState({ name: value });
};
onChange={this.handleChange("anySearch")}
But this doesn't work anymore. State now shows only one letter at a time when console logged.
What is best practice to filter according to multiple different criteria à la kayak, and how do I rewrite the handleChange function without pushing each letter into an array?
handleChange = name => event => {
const value = event.target.value;
this.setState({ name: value });
};
your idea of returning a function is correct, you just have an error when setting the state
this.setState({ name: value });
change it to
this.setState({ [name]: value });
Regarding the second question, you can simply iterate over your array and filter out the objects that match that specific criteria, to avoid unnecessary overhead you can implement a caching mechanism that keep track of the searches the user has already done.
something like this:
function filter(criteria) {
if(cache[criteria]) {
return cache[criteria];
}
cache[criteria] = myArray.filter(elem => elem.criteria === criteria);
return cache[criteria];
}