Reputation: 367
I am trying to update a videoId using state, but when the state changes, it does not update my component for some reason.
I've tried to spread the new data, but that isn't working either.
Here is my code:
const exercises = [
{
id: 1,
videoSrc:video,
},
{
id: 2,
videoSrc: video
},
{
id: 3,
videoSrc: video
},
{
id: 4,
videoSrc: video
},
];
export function WarmUpContent() {
const [videoId, setVideoId] = useState(1);
const [videoSrc, setVideoSrc] = useState(exercises[0].videoSrc);
function handleNext() {
setVideoId(videoId + 1);
console.log(videoId);
const result = exercises.find(({ id }) => id === videoId);
const video = result.videoSrc;
setVideoSrc([...video]);
}
return (
<>
<div className="">
<div className="mb-4">
<VideoPlayer src={videoSrc} />
</div>
<div className="">
<Button onClick={() => handleNext()} size="slim">
Next
</Button>
</div>
</div>
</>
);
}
Upvotes: 1
Views: 30
Reputation: 191936
The state is updated asynchronously, so the new state would only be available on the next render. A simple solution is to calculate the new id, and then set the state, and use to get the video src:
function handleNext() {
const newId = videoId + 1;
setVideoId(newId);
const result = exercises.find(({ id }) => id === newId);
const video = result.videoSrc;
setVideoSrc(video); // don
}
However, a better solution would be use only a single state (videoId
). Update the videoId
and then calculate the derived data (videoSrc
) during render:
export function WarmUpContent() {
const [videoId, setVideoId] = useState(1);
function handleNext() {
setVideoId(id => id + 1); // use the update function when the value is dependent on prev value
}
const videoSrc = useMemo(() => {
const result = exercises.find(({ id }) => id === videoId);
return result.videoSrc;
}, [videoId]);
return (...);
}
Upvotes: 2