25
loading...
This website collects cookies to deliver better user experience
$ yarn develop
http://localhost:1337/admin/
, once you are there enter the login data for the admin user. Content-Types Builder
and this will bring you to the list of your content type so click Create Content Type
.BlogPost
and press Continue, next you will be prompted to select a field for our content type:http://localhost:1337
.frontend
folder create a new directory under src
named queries
there create a new file named blogPosts.js
.import { gql } from '@apollo/client'
export const GET_BLOGPOSTS = gql`
query {
blogPosts {
id
Title
Body
Tags
CreatedAt
}
}`
ListBlogPosts.js
inside frontend/src/components
import React from 'react'
import { GET_BLOGPOSTS } from "../queries/blogPosts"
import {useQuery} from "@apollo/client";
function ListBlogPosts() {
const {data, error, loading} = useQuery(GET_BLOGPOSTS)
if(loading) return 'Loading...'
if(error) return `Oops there has been an error: ${error}`
if(data) return console.log(data)
}
export default ListBlogPosts
yarn start
and navigate to http://localhost:3000
you will see ..this:Oops there has been an error: Error: Forbidden
Settings
and under Users & Permissions Plugin
section select Roles
. There you will see our BLOG-POSTS
with all checkboxes deactivated, use select all
to check all boxes and save it.http://localhost:3000
you will see nothing but when you open console you will see we get the object. Success! Now let's show that in a way we humans understand it. Remove the line with if(data)...
and create this return instead:...
if(error) return `Oops there has been an error: ${error}`
return(
<div>
<h1>List of Blog Posts</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Title</th>
<th>Body</th>
<th>Tags</th>
<th>Created</th>
</tr>
</thead>
{data?.blogPosts && data?.blogPosts.length !== 0 ?
<tbody>
{data?.blogPosts.map(({id, Title, Body, Tags, CreatedAt}) => (
<tr key={id}>
<td>{id}</td>
<td>{Title}</td>
<td>{Body}</td>
<td>{Tags}</td>
<td>{CreatedAt}</td>
</tr>
))}
</tbody> : <tbody><tr><td>No Blog Posts to show!</td></tr></tbody>}
</table>
</div>
)
export default ListBlogPosts
data?.
with question mark, that is optional chaining because we don't want our code to throw exception if the data is somehow not ok. First we are checking whether blogPosts are there and whether we have blogPosts, we use .length
here because we get an array of blogPosts so if there are blogPosts the .length
won't be 0. If there are no blogPosts we show short info that there is no blog posts to show while if there are blogPosts we show them in the table through the map function.