This works. I’m not sure why, but separating the Player component in other component I can update the component from the button callback.
Just to explain the use of useState here: the videoId
attribute is saved in the comment delimiter block when saving the post. That is something that has already been achieved, it is not a problem. That I needed is a way to preview the video in a player inside the editor when it was chosen in the TextControl
component.
This player cannot be rendered with the Texcontrol
onChange
callback because it will try to update with each character typed. For that reason I have included a button that updates the player when the ID is already fully written.
export default function Edit({ className, attributes, setAttributes }) {
const [video, setVideo] = useState("");
const addVideo = () => {
setVideo(attributes.videoId);
};
const AgVideo = () => {
return (
<Player controls>
<Youtube videoId={video} />
</Player>
);
};
return (
<div {...useBlockProps()}>
<div>
<TextControl
label="YouTube video ID"
help="Algo parecido a: DyTCOwB0DVw"
className={className}
value={attributes.videoId}
onChange={(val) => setAttributes({ videoId: val })}
/>
<Button isPrimary onClick={addVideo}>
Añadir vídeo. añadido: {video}
</Button>
<AgVideo />
</div>
</div>
);
}