Search code examples
javascriptreactjscontentfulcontentful-api

Contentful API with React how to get specific fields from array items instead of whole arrays


I'm was trying to look for ways to make my website load faster and after running speed tests I understood that I was making a mistake in the way I'm loading data from contentful. I have a page with all the blogs listed in it (with just their title and image and a handful other details visible in the list of blogs) and instead of loading only the necessary fields from contentful I'm loading all the fields for each array item(post) of the array posts which naturally takes up a lot of time and makes my page slow. How can I load only specific fields from contentful for the blog list page but load all the fields when we click on an individual blog from the list. I'm using react static and this is how my config file looks for the posts section where the path /blog is the main blog list page and /container/Post is the individual blog page.

let posts = await client
      .getEntries({
        content_type: "blogPost",
        order: "-sys.createdAt",
        include: 1,
      })
      .then((response) => response.items)
      .catch(console.error);
    console.log("Post -> ", posts.length);

    posts = posts.sort((a, b) => {
      let keyA = new Date(a.fields.date);
      let keyB = new Date(b.fields.date);
      // Compare the 2 dates
      if (keyA < keyB) return 1;
      if (keyA > keyB) return -1;
      return 0;
    });

And in my return statement

{
        path: "/blog",
        getData: () => ({
          posts,
        }),
        children: posts.map((post) => ({
          path: `/${urlBuilder(
            post.fields.url ? post.fields.url : post.fields.title
          )}`,
          template: "src/containers/Post",
          getData: () => ({
            post,
          }),
        })),
      },

This is how my posts returned from contentful looks like

enter image description here


Solution

  • You can achieve this using the select operator. What this translates into when using the contentful sdk is something like this:

    const contentful = require('contentful')
    
    const client = contentful.createClient({
      space: '<space_id>',
      environment: '<environment_id>',
      accessToken: '<content_delivery_api_key>'
    })
    
    client.getEntries({
      content_type: '<content_type_id>',
      select: 'sys.id,fields.<field_name>'
    })
    .then((response) => console.log(response.items))
    .catch(console.error)
    

    Pay special attention to the select: 'sys.id,fields.<field_name>' section. This is where you can specify only what fields you want returned.