apiFetch package is a very useful utility in WordPress. It helps to retrieve data from the REST API endpoint, for example. Here’s the usage for a default REST API endpoint: https://localhost/wp-json/wp/v2/posts.

// GET
apiFetch( { path: '/wp/v2/posts' } ).then( ( posts ) => {
    console.log( posts );
} );
 

If you want to enable REST API for your custom post types, here’s the documentation.


The one thing to note down however is the result of the apiFetch is a JavaScript promise. So, it’s handled asynchronously. This means you cannot get the result of the promise immediately to use later in your code. So, something like this won’t work.

const wp_posts = apiFetch( { path: 'wp/v2/posts' } ).then( ( posts ) => {
    return posts;
} );

console.log( wp_posts);

You’ll still get the value of wp_posts as a promise.


So, how to get the data?

Using the React Hooks useState and useEffect. useState allows us to add React state to functional components. So, we’ll set the Posts retrieved from the promise using useState so that we can use it later.

const [posts, setPosts]	= useState( null );
const [gotPost, setGotPost ] = useState( false );

Then we’ll just set the posts from the result of a promise.

	useEffect( () => {
		apiFetch( { path: '/wp/v2/posts ).then(
			(result) => {

				setGotPost(true);
				setPost( result );
			}
		)
	}, []);

Now, we can retrieve the result of a promise from the post constant so that wherever you write console.log( posts ), you’ll get the result of promise instead of promise itself.


Why useEffect?

We’re wrapping the function under useEffect because the posts need to be set after the render. Think of it as the effects (setting the posts) happen “after render”. The empty deps array [] means this useEffect will run once. This is absolutely required because you don’t set posts on every render leaking the memory.


I hope this helps! 🙂

Get data from the promise of WordPress apiFetch
Tagged on:

Sanjeev Aryal

Don't bury your thoughts, put your vision into reality ~ Bob Marley.

Leave a Reply

Your email address will not be published. Required fields are marked *

Pin It on Pinterest