Skip to content

Commit

Permalink
Docs/iAPI: Fix wrong code snippet in data-wp-run example (WordPress#6…
Browse files Browse the repository at this point in the history
…2835)

* Fix wrong code snippet in wp-run example

* Add explanation/warning about using `ref` inside `data-wp-run`

Co-authored-by: luisherranz <[email protected]>
Co-authored-by: fabiankaegy <[email protected]>
  • Loading branch information
3 people authored Jun 25, 2024
1 parent a789146 commit 90bc142
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions docs/reference-guides/interactivity-api/api-reference.md
Original file line number Diff line number Diff line change
Expand Up @@ -535,13 +535,14 @@ import { store, useState, useEffect } from '@wordpress/interactivity';

// Unlike `data-wp-init` and `data-wp-watch`, you can use any hooks inside
// `data-wp-run` callbacks.
const useInView = ( ref ) => {
const useInView = () => {
const [ inView, setInView ] = useState( false );
useEffect( () => {
const { ref } = getElement();
const observer = new IntersectionObserver( ( [ entry ] ) => {
setInView( entry.isIntersecting );
} );
if ( ref ) observer.observe( ref );
observer.observe( ref );
return () => ref && observer.unobserve( ref );
}, []);
return inView;
Expand All @@ -550,8 +551,7 @@ const useInView = ( ref ) => {
store( 'myPlugin', {
callbacks: {
logInView: () => {
const { ref } = getElement();
const isInView = useInView( ref );
const isInView = useInView();
useEffect( () => {
if ( isInView ) {
console.log( 'Inside' );
Expand All @@ -565,6 +565,8 @@ store( 'myPlugin', {
```
</details>

It's important to note that, similar to (P)React components, the `ref` from `getElement()` is `null` during the first render. To properly access the DOM element reference, you typically need to use an effect-like hook such as `useEffect`, `useInit`, or `useWatch`. This ensures that the `getElement()` runs after the component has been mounted and the `ref` is available.

### `wp-key`

The `wp-key` directive assigns a unique key to an element to help the Interactivity API identify it when iterating through arrays of elements. This becomes important if your array elements can move (e.g., due to sorting), get inserted, or get deleted. A well-chosen key value helps the Interactivity API infer what exactly has changed in the array, allowing it to make the correct updates to the DOM.
Expand Down

0 comments on commit 90bc142

Please sign in to comment.