Thanks so much for your help @mburridge! You were right, I was calling the value before checking if it existed.
The reason why I was trying to use const nextPost = state.source[data.type][post.next.id]
was because I couldn’t use just the slug as the link location as my posts have the categories in their URLs, so the link was going to a URL that was “domain.com/post-name” when I needed it to be “domain.com/category/post-name” so I was trying to reach out to the post using the ID in that const variable, then grabbing the link
property from there - I believe this is where I was running into the Internal Server Error issues.
To solve this, I went back to my functions.php
file and adjusted the code to include the relative path as a link property in the API with this:
/* Add next & previous links to REST API */
add_filter( 'rest_prepare_post', 'add_prev_next_to_rest' , 10, 3 );
function add_prev_next_to_rest( $response, $post, $request ) {
global $post;
// Get the next post.
$next = get_adjacent_post( false, '', false );
//Get next post url and relative link
$nextPostUrl = get_permalink( get_adjacent_post(false,'',false)->ID );
$nextPostLink = wp_make_link_relative( $nextPostUrl );
// Get the previous post.
$previous = get_adjacent_post( false, '', true );
//Get previous post url and relative link
$prevPostUrl = get_permalink( get_adjacent_post( false, '', true )->ID );
$prevPostLink = wp_make_link_relative( $prevPostUrl );
// Only send id and slug (or null, if there is no next/previous post).
$response->data['next'] = ( is_a( $next, 'WP_Post') ) ? array( "id" => $next->ID, "slug" => $next->post_name, "link" => $nextPostLink ) : null;
$response->data['previous'] = ( is_a( $previous, 'WP_Post') ) ? array( "id" => $previous->ID, "slug" => $previous->post_name, "link" => $prevPostLink ) : null;
return $response;
}
Then, I modified your conditional link to be:
{ nextPost ? <Link link={nextPost.link}>Next</Link> : ''}
{ prevPost ? <Link link={prevPost.link}>Previous</Link> : ''}
And this seems to have solved all my issues! Sorry I know that was a lengthy response but I figured I would include everything in case anyone else was looking for a similar solution.
Thanks again, @mburridge! You really helped.