Utilizing the URL path name for data retrieval in Next.js 14 - A step-by-step guide

I'm currently developing a blog using AWS Amplify Gen 2 and GraphQL for a Next.js 14 project with TypeScript. As part of my application, I need to fetch specific data based on the URL path name. Here's how I've approached it:

My approach involves utilizing a component called Article:

'use client';
import { usePathname } from "next/navigation";

export default function Article() {
    const slug = usePathname().split('/').pop();
    return slug;
}

Within my app, I have a page.tsx file located at app/articles/[slug]:

import type { Schema } from '@/amplify/data/resource';
import { generateClient } from 'aws-amplify/data';
import Article from '@/components/article/article';

const client = generateClient<Schema>();

async function fetchPosts() {
    const { data: posts } = await client.models.Posts.list();
    return posts;
}

export default async function ArticlePage() {
    const posts = await fetchPosts();
    return (
        // I aim to retrieve and display posts that match the slug value in the URL path
    );
}

I am looking to modify ArticlePage so that it can fetch and present the posts that correspond to the slug value found in the URL path. How can this be achieved?

The key details are: I'm working with Next.js 14 and TypeScript. The client.models.Posts.list() function retrieves all posts, but I require them to be filtered based on the slug value from the URL path.

EDIT:

The code snippet below accomplishes the task, yet instead of a static String, I want the slug to derive from the URL path ("/articles/my-first-post" or "/articles/my-second-post").

import type { Schema } from '@/amplify/data/resource';
import { generateClient } from 'aws-amplify/data';

const client = generateClient<Schema>();

async function fetchPosts() {
    const { data: posts, errors } = await client.models.Posts.list();
    return posts;
}

export default async function Article() {
    const slug = 'my-first-post'; // This should dynamically come from the URL path
    const posts = await fetchPosts();
    const filteredPosts = posts.filter(post => post.slug === slug);

    return (
        <div>
            {filteredPosts.map(post => (
                <div key={post.createdAt}>
                    <h2>{post.title}</h2>
                    <p>{new Date(post.createdAt).toLocaleDateString()}</p>
                    <p>{post.content}</p>
                </div>
            ))}
        </div>
    );
}

Answer №1

If you're looking for a solution, consider this:

async function retrieveSelectedPosts(slug) {
    const { data: posts } = await client.models.Posts.list();
    return posts.filter((post) => post.id === slug); // Adjust as needed
}

export default async function DisplayArticle({ params }: { params: { slug: string } }) {
    const selectedPosts = await retrieveSelectedPosts(params.slug);
    return (
        ...
    );
}

This approach should suffice and eliminate the need for the Article component's code block.

An alternative method would involve utilizing client.models.Posts.list(slug) to filter the relevant posts directly. This could potentially improve efficiency.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Having issues implementing Pinterest tag through Google Tag Manager

After following Pinterest's instructions to add the Pinterest tag to my Next.js website using a no-code implementation method, I encountered an issue. While my Google Tag is working fine and events are being tracked successfully, the Pinterest tag doe ...

Ensure that the key and value types in a Typescript Map are strictly specified

Is it feasible to generate a map that consists of key-value pairs, where the key is represented by a string and the value corresponds to an object containing specific properties defined by mapValue? type mapValue { first: string; second: boolean; } Yo ...

Initiating the node js service locally

I have been working on a Node.js and Gradle application, but I'm having trouble figuring out how to run it locally. So far, I've done the Gradle build (./gradlew) and NPM run build (compile), with all my dependencies neatly stored in the node_mo ...

Error when compiling TypeScript: The callback function provided in Array.map is not callable

This is a Node.js API that has been written in Typescript. app.post('/photos/upload', upload.array('photos', 12), async (req, res) => { var response = { } var list = [] try { const col = await loadCollection(COLLECTION_NAM ...

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

When utilizing gapi (typescript) to send emails, the Sent box may contain incorrectly encoded email messages

When I send emails using gapi, the receiver receives them correctly. However, when I check my "Sent" box, the emails appear as Chinese gibberish characters like in this image. This issue only occurs when using non-gmail applications. If I view the Sent bo ...

Ensure the presence of a value in an array using Angular

I need to check if any of the "cuesData" have values or lengths greater than 0. However, in my current code, I can only evaluate the first array and not the rest. https://i.sstatic.net/bMpvg.jpg TS checkValues(values) { const result = Object.values ...

The functionality of getStaticProps is not operational when being used within the components

Following a recent issue I encountered, the question arises: typeError: Cannot read property 'map' of undefined. I attempted to utilize a component with getStaticProps in my pages/index.js, but alas, it doesn't function properly in conjunct ...

Input values that are true, or in other words, fulfill conditions for truthiness

Is there a specific data type in TypeScript to represent truthy values? Here's the method I'm working with: Object.keys(lck.lockholders).length; enqueue(k: any, obj?: any): void It seems like TypeScript allows checking for empty strings &ap ...

click event on ion card

Attempting to handle a click event within an ion-card using Ionic 5.0.2 version has presented some challenges. Despite my efforts, I have not been successful in handling the event with the expected function. Here is a snippet of my code: Dynamic card list ...

Explore the world of video streaming with Next js 13.4!

I am encountering an issue with video streaming while working on a full-stack project in nextJS. I have implemented the new GET method strategy to fetch streams in next and here is my front-end code that requests the API to retrieve the streams: &l ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

Exploring the depths of Javascript objects using Typescript

If I have this specific dataset: data = { result: [ { id: '001', name: 'Caio B', address: { address: 'sau paulo', city: 'sao paulo', ...

It appears that when importing from a shared package in lerna, the name must include "src" at the end for Typescript or Javascript files

I am currently working on a straightforward lerna project structure as shown below: Project | +-- packages | | | +-- shared | | | | | +-- src | | | | | +-- index.ts | | +-- someDir | | | +-- usesShared | ...

The instanceof operator does not recognize the value as an instance and is returning false, even though it

Is there a method to verify the current instance being used? This is what I am logging to the console: import { OrthographicCamera } from 'three'; // Later in the file: console.log(camera instanceof OrthographicCamera, camera); and the result ...

"Silently update the value of an Rxjs Observable without triggering notifications to subscribers

I'm currently working on updating an observable without alerting the subscribers to the next value change. In my project, I am utilizing Angular Reactive Forms and subscribing to the form control's value changes Observable in the following manner ...

An issue occurred in the modal window following the relocation of project files

I encountered an issue with the modal in my Nativescript project after rearranging a few project files, including the modal. I updated the imports and deleted any compiled JavaScript files to ensure that my project could recompile correctly. Although I&ap ...

How can Angular CLI prevent the submission of an HTML form unless a previous option has been selected

I am currently working on a form that contains select fields with various options pre-populated. <form [formGroup]="selectVehicleForm"> <select formControlName="Manufacturer"> <option *ngFor='let ...

Incorporating quotes into a unified npm script

I'm trying to merge two npm scripts into one, but the result is incorrect and causes issues with passing flags. I can't use the dotenv package, and using ampersands isn't solving the problem. Here's what I have in my package.json file ...

What are the acceptable key-value pairs that can be used in the parameters.json file for AWS Amplify?

I have a file called parameters.json in my AWS Amplify project that contains various key/value pairs. I am interested in learning all the available pairs. { "AppSyncApiName": "name", "DynamoDBBillingMode": "PROVISIONE ...