Unable to fetch Title from Strapi

I have a collection type named posts with the following values:

https://i.sstatic.net/49OeV.png

To access the API, I have a file in my lib folder that contains the following code:

export async function getPosts() {
var api_base_url = process.env.API_BASE_URL;
const response = await fetch(api_base_url + "/posts");
const posts = await response.json();
return posts;
}

export async function getPost(postId) {
    var api_base_url = process.env.API_BASE_URL;
    const response = await fetch(api_base_url + "/posts/" + postId);
    const post = await response.json();
    return post;
}

export async function getPostFromTitle(postTitle, lang) {
    var api_base_url = process.env.API_BASE_URL;
    const response = await fetch(api_base_url + "/posts");
    const posts = await response.json();
    var postObject = {};
    posts.forEach(post => {
        if (post['Title (' + lang.toUpperCase() + ')'] == postTitle) {
            postObject = post;
        }
    });
    return postObject;
}

To display this data, I used the following code:

import { getPosts, getPostFromTitle } from '../lib/apiGet'

export async function getStaticProps() {
  const allPosts = JSON.parse(JSON.stringify(await getPosts()));
  const postsTitle = JSON.parse(JSON.stringify(await getPostFromTitle(postTitle, lang)));
  
  return {
    props: {
      allPosts,
      postsTitle
    }
  }
}

export default function Home({ allPosts, postsTitle }) {
  return (
    <div>
      <body>            
        <ul>
        {allPosts.map(post => (
            <h1><u>
            {console.log(post.id)}
              {post.id}
            </u>            
            </h1>
          ))}
        </ul>
        <ul>
        {postsTitle.map((postTitle, lang) => (
            <h1><u>
            {console.log(postTitle.Title)}
              {postTitle.Title}
            </u>            
            </h1>
          ))}
        </ul>
      </body>
    </div>
  );
}

I can retrieve the id correctly, but encountering an error when trying to print the Title.

https://i.sstatic.net/gXmkh.png

How can I properly retrieve the title?

Answer №1

It appears that the issue could be related to your frontend function;

export async function getPostFromTitle(postTitle, lang) {
    var api_base_url = process.env.API_BASE_URL;
    const response = await fetch(api_base_url + "/posts");
    const posts = await response.json();
    var postObject = {};
    posts.forEach(post => {
        if (post['Title (' + lang.toUpperCase() + ')'] == postTitle) {
            postObject = post;
        }
    });
    return postObject;
}

There may not be any posts returned by this function - I recommend debugging it. Are the objects in the "posts" const valid? Is the return value correct or is it undefined?

In general, a simpler approach would be rewriting the filtering part of your function (everything after await response.json();) to utilize the JavaScript filter function.

You can try something like this;

return posts.filter(post => post['...'].includes(postTitle));

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

Deciphering the functionality of req.flash()

I'm finding myself confused about how to use req.flash in node.js. For example, I have a .catch block that looks like this: Login function .catch(function(e){ req.flash('errors', 'error here') res.redirect('/') }) ...

Two tags attached to four hypertext links

Within my HTML code, I have hyperlinks present on every line. However, I am seeking to eliminate these hyperlinks specifically from "your previous balance" and "your new balance". In the following HTML snippet: <tr *ngFor="let l of statementLines; ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Issue with Vue2's v-text functionality

Recently, I've delved into Vue2 and encountered a problem with form submission and validation on a single page. The issue lies in the error display process – I want errors to be shown beneath each form input as soon as they occur, rather than waitin ...

Display a fixed three levels of highchart Sunburst upon each click in Angular8

Looking to create a dynamic sunburst highchart that displays three levels at a time while allowing interactive drilling. For instance, if there are 5 levels, the chart should initially show the first three levels. When clicking on level 3, levels 2, 3, and ...

Tips for correctly deleting a duplicate ref Object ID following the removal of a Document

Coming from a background in relational databases, I'm encountering a challenge with a pattern in Mongoose. Let's say we have SchemaA and SchemaB (for example, pets and people): const Person = new Schema({ name: String, pets: [{ ref: ...

Sending STATIC_URL to Javascript file in Django

What is the most effective method for transferring {{ STATIC_URL }} to JavaScript files? I am currently using django with python. Thank you in advance. Best regards. ...

How to retrieve the type of a computed keyof T as a generic type within TypeScript

I am working with two different interfaces: interface PersonRequirements{ user:string, password:string, id:number } export interface Requirement<R> { name: keyof R & string, save: () => any,/* I want this return type to be ...

What is the best way to resize an element such as an image?

When an image is resized using a percentage, it preserves its aspect ratio properly. I am looking for a way to replicate this behavior with a div. My current challenge involves precisely positioning an element relative to an image. The image fills 100% of ...

Updating the text input value in a database with PHP upon button click

Here is a breakdown of what has been implemented so far: The database table is named adhar_card. Below is the structure image for reference (Adhard_card_id serves as the primary key). https://i.sstatic.net/8j4m6.jpg Clicking on the verify button will cha ...

What is the best method for transmitting server errors to the client?

When using passport.js, I have all the required code in place. However, I am facing an issue with displaying errors on the client-side. Despite having the successRedirect set up correctly, nothing happens when a wrong password is entered, and no error mess ...

What's the deal with this error message saying val.slice isn't a function?

In the process of developing a web application using express with a three-tier architecture, I have chosen to use a mysql database to store blogposts as a resource. Here is an illustration of how the table is structured: CREATE TABLE IF NOT EXISTS blogpos ...

Dynamic SVG positioning

Looking for a way to make this svg shape relative to its containing div? Fiddle: http://jsfiddle.net/8421w8hc/20/ <div> <svg viewBox="0 0 1000 2112" style="" xmlns="http://www.w3.org/2000/svg" version="1.1"> <path id="ma" st ...

What is the best way to hide a custom contextmenu in AngularJs?

I created a custom contextmenu directive using AngularJs. However, I am facing an issue where the menu is supposed to close when I click anywhere on the page except for the custom menu itself. Although I have added a click function to the document to achie ...

Changing the color of a specific span using Angular

I am working with a dynamic mat-table where columns are added and populated on the fly. The table headers are styled using divs and spans. My goal is to change the color of a header to black when clicked, but also un-toggle any previously selected header. ...

Issue encountered while attempting to install datagrid library with Nuxt3

Currently, I am working on a Nuxt3 project and attempting to integrate the " @revolist/vue3-datagrid" library. Following the instructions provided in the library's documentation, I executed the command "npm i @revolist/vue3-datagrid --save". Unfortuna ...

Divide a SINGLE BACKGROUND IMAGE in HTML into two separate links of equal size, one at the top and

As a beginner in HTML, I am trying to find a way to divide a background image into two equal sections without using image mapping. I attempted to split the links by setting the style to 0% and 50% to designate the top and bottom halves, but unfortunately, ...

How to delete the last item of an array in AngularJS using scope

In my Angular controller, I have an array and a method for deleting objects. function($scope, $http){ $scope.arrayOfObjects = []; $scope.remove = function(obj){ var i = $scope.arrayOfObjects.indexOf(obj); if( i > -1 ){ ...

Express Node.js Error: Address Information Syntax Issue

While developing my server using TypeScript for my Angular app to connect to, I encountered an issue when trying to run the code snippet below. It seems that Node.js or TS is not yet compatible with certain ES6 features like destructuring with AddressInfo, ...

What is the best way to fetch the most recent article from every category using mongodb?

I am currently working with the following article schema: var articleSchema=new Schema({ id : Number, title : String, sefriendly : String, created : Date, categories: [ { id: Number, name: String, ...