0

I am making a blog using NextJs and Prismic CMS. On page load data is displayed and passing data from <Blog /> through <cards-list ?> and finally to <Card />.

On a loadmore button, a call is made to get the next round of posts to display, but when doing so it errors at all of the prop values in <Card />.

Index

import { Fragment, Component } from 'react';
import { Client } from '../../prismic-configuration';
import Prismic from "prismic-javascript";
import { RichText } from "prismic-reactjs";
import axios from 'axios';

import Layout from '../../components/Layout';
import HeadElement from '../../components/HeadElement';
import Header from '../../components/Header';
import Footer from '../../components/Footer';
import { CardList } from '../../components/card/CardList';
import { FilterList } from '../../components/filter/FilterList';

class Blog extends Component {

  constructor() {
    super();

    this.state  = {
      pageNum: 1,
      posts: []
    };

  } // END constructor

  static async getInitialProps(context) {

    const req = context.req;

    const posts = await Client(req).query(
      Prismic.Predicates.at("document.type", "news"),
      { 
        orderings: "[document.first_publication_date desc]",
        pageSize : 1,  // default value is 20
        page : 1
      },
    );

    const postCategories = await Client(req).query(
      Prismic.Predicates.at("document.type", "post_categories")
    )

    return {
      posts: posts ? posts.results : [],
      categories: postCategories ? postCategories.results : []
    }

  } // END getInitialProps

  componentDidMount = () => {
    this.setState({ posts: this.props.posts });
  } // END componentDidMount

  loadMoreHandler = () => {

    // Increase page number on click for pagination
    this.setState({ pageNum: this.state.pageNum + 1 });
    let pageNum = this.state.pageNum;

      axios({
        method: 'GET',
        url: `https://mycms.cdn.prismic.io/api/v2/documents/search?ref=_ref_here&q=[[at(document.type, "news")]]&pageSize=1&page=${pageNum}`
      })
        .then(response => {

          const data = response.data.results;
          console.log('data', data);

          // Append data to array in state
          // this.setState({ posts: [...this.state.posts, data] });

        },
          (error) => {
            console.log(error);
          });

  } // END loadMoreHandler

  render() { 

    console.log(this.state.posts);

    return (
      <Fragment>

      <HeadElement 
        bodyClass="news" 
        metaTitle="News"
        metaDescription="Latest property news & local insights from Mr Investa."
        />

      <Header />

      <Layout>

        <header className="article-header">
          <h1>News</h1>
          <p>Latest property news & local insights</p>
          <FilterList categories={this.props.categories} />
        </header>
       
        <CardList posts={this.state.posts} />

        <div className="btn-center">
          <div 
            className="btn"
            onClick={this.loadMoreHandler}
          >
            Load more
          </div>
        </div>

        <Footer />

      </Layout>

      </Fragment>
    )

  }

}

export default Blog;

CardList

import React from 'react';
// import { Card } from './Card';
import Card from './Card';

export const CardList = props => {
  return (
    <div className="container">
      <div className="card-list">
        {props.posts.map((post, i) => (
          <Card key={i} post={post} />
        ))}
      </div>
    </div>
  )
}

Card

// import React from 'react';
import { Component } from 'react';
import { Link } from 'prismic-reactjs';
import { default as NextLink } from 'next/link';
import { hrefResolver } from '../../prismic-configuration';
import { linkResolver } from '../../prismic-configuration';
import { PostDate } from '../utils/PostDate';
import { matchHeights } from '../../src/utils/helpers.js';

class Card extends Component {

  componentDidMount() {

    matchHeights('[data-matchheights]');

  } // END componentDidMount

  render() {

    // TODO: `props` isn't getting the data now were using state .....

    const props = this.props;
    // const props = this.state;

    return (
      <article className="card">
        <NextLink
          as={linkResolver(props.post)}
          href={hrefResolver(props.post)}
        >
          <a>
            <div className="card__img">
              <img src={props.post.data.featured_image.url} alt={props.post.data.featured_image.alt} />
            </div>
            <span className="card__date">
              <PostDate date={props.post.first_publication_date} />
            </span>
            <div className="card__text" data-matchheights>
              <h2 className="card__title">{ props.post.data.title[0].text }</h2>
              <span className="card__excerpt">{props.post.data.excerpt[0].text}</span>
              <strong>Read more ›</strong>
            </div>
          </a>
        </NextLink>
      </article>
    )

  }

}

export default Card;

If anyone can assist with troubleshooting the issue it would be appreciated :)

moody1208
  • 437
  • 1
  • 4
  • 19

1 Answers1

0

I fixed the issue by looping over the items in the returned data.... daft moment!

 data.map(data => {
            this.setState({ posts: [...this.state.posts, data] });
          });
moody1208
  • 437
  • 1
  • 4
  • 19