Answers for "use state value change right after setState or state update"

1

use state value change right after setState or state update

const buttonClick = (e) => {
		console.log(e.target.innerText);
		let pressedKey = e.target.innerText;
		// let soundName;

		sounds.forEach((item) => {
			if (pressedKey === item.keyTrigger) {
				setSoundFile(item.url);
				// soundName = item.id;
			}
		});
	};
    
    // state updated on button click. use that update in a useEffect 
    // because setState is asynchronous. update will not yet take effect.
    
    useEffect(() => {
		if (soundFile) {
			const audioElement = new Audio(soundFile);
			audioElement.play();
		}
	}, [soundFile]);
Posted by: Guest on April-02-2021
1

use state value change right after setState or state update

setMovies(result);
console.log(movies) // movies here will not be updated

so do it in useEffect

useEffect(() => {
    // action on update of movies
}, [movies]);

https://www.google.com/search?q=can+i+use+state+value+in+function+immediately+after+setting+it&oq=can+i+use+state+value+in+function+immediately+after+setting+it&aqs=chrome..69i57j69i64.10511j0j7&sourceid=chrome&ie=UTF-8
Posted by: Guest on April-02-2021

Browse Popular Code Answers by Language