I am trying to connect contentful and Gatsby for a blog.
const path = require('path');
exports.createPages = ({ graphql, boundActionCreators }) => {
const { createPage } = boundActionCreators;
return new Promise((resolve, reject) => {
const blogPostTemplate = path.resolve('src/templates/blog-post.js');
resolve(
graphql(`
{
allContentfulBlog(limit: 100) {
edges {
node {
id
slug
}
}
}
}
`).then(result => {
if (result.errors) {
reject(result.errors);
}
result.data.allContentfulBlog.edges.forEach(edge => {
createPage({
path: edge.node.slug,
component: blogPostTemplate,
context: {
slug: edge.node.slug
}
});
});
return;
})
);
});
};
This is what I wrote in the gatsby-node.js. When I do npm run develop, it gives me an error, saying " TypeError: Cannot read property 'allContentfulBlog' of undefined." I am not sure how I should fix this. Anyone got an idea?
I ran into the same difficulties, I'm assuming you were following this youtube tutorial by khaled and try to check it out by using the default contentful Blog template like so:
Make sure you are using the CORRECT contentModelName when writing the allContentful{contentModelName} post. When using the default blog example for contentful the title shows up as "Blog Post". Just change it from "Blog Post" to "Blog" and everything should be working fine if you followed Khaled's steps and added the "new Promise" fix (which I see you already did).
Good luck!
Related
I've been learning the mern stack from this book
I'm now on Nested Routes under React Router chapter
The web application is supposed to render this on the page.
When clicking the Select link under the Action column, the description of
an issue is displayed on the bottom part of the page.
But in my case, this thing happens:
and at the same time this error is being thrown in the console:
The only time the web application runs properly is when I downgraded the
graphql version to 0.13.2 (this is the version the book uses).
The thing is I try to use up to date versions of the project dependencies
as much as possible. There has never been much trouble as I follow the book
until I got into this.
I don't understand, why is this error being thrown when I use a more up to
date version of the graphql over the old version?
(I use graphql version 15.8.0 and apollo-server-express version 2.25.4)
I tried to modify the .jsx file that renders the description data
on the page.
async loadData() {
const { match: { params: { id } } } = this.props;
//I tried to parse the id to make it an int type before getting it into
//the graphql query
id = parseInt(id); // this is the thing that I've added
const query = `query issue($id: Int!) {
issue (id: $id) {
id description
}
}`;
const data = await graphQLFetch(query, { id });
if (data) {
this.setState({ issue: data.issue });
} else {
this.setState({ issue: {} });
}
}
This is the codes graphQLFetch function
const dateRegex = new RegExp('^\\d\\d\\d\\d-\\d\\d-\\d\\d');
function jsonDateReviver(key, value) {
if (dateRegex.test(value)) return new Date(value);
return value;
}
async function graphQLFetch(query, variables = {}) {
try {
const response = await fetch(window.ENV.UI_API_ENDPOINT, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ query, variables }),
});
const body = await response.text();
const result = JSON.parse(body, jsonDateReviver);
if (result.errors) {
const error = result.errors[0];
if (error.extensions.code === 'BAD_USER_INPUT') {
const details = error.extensions.exception.errors.join('\n');
alert(`${error.message}:\n ${details}`);
} else {
alert(`${error.extensions.code}: ${error.message}`);
}
}
return result.data;
} catch (e) {
alert(`Error in sending data to server: ${e.message}`);
return null;
}
}
When I did this, it doesn't throw any error anymore but it doesn't render
the description data on the page either.
Can someone please help me with this?? Thanks in advance...
I am using ionic with firebase realtime database and capacitor 3. I intend to enable offline capabilities. I have built the app using ionic cap build and then opened in xcode. Then following url https://firebase.google.com/docs/database/ios/offline-capabilities I added the below code in AppDelegate.swift
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
FirebaseApp.configure()
Database.database().isPersistenceEnabled = true
return true
}
Now to test i ran the app with wifi on and got the data from firebase db. after this i killed the app and turned off wifi. However, on launching the app it does not load the data.
Is there anything else i am missing here?
my key pod file has:
target 'App' do
capacitor_pods
# Add your Pods here
pod 'FirebaseCore', '7.11.0' # Add this line
pod 'Firebase/Database', '7.11.0' # Add this line
end
Below is my code that does not work and expected to:
getSeedConfig(){
return new Promise((resolve, reject) =>{
const doc = ref(this.db, 'config/seed');
get(doc).then((snapshot) => {
if (snapshot.exists()) {
resolve(snapshot.val())
} else {
resolve(null)
}
}).catch((error) => {
reject(error)
});
})
}
When using a modern API in JavaScript there are not many cases where you need to return a custom promise anymore.
As far as I can tell this code that you now have:
getSeedConfig(){
return new Promise((resolve, reject) =>{
const doc = ref(this.db, 'config/seed');
get(doc).then((snapshot) => {
if (snapshot.exists()) {
resolve(snapshot.val())
} else {
resolve(null)
}
}).catch((error) => {
reject(error)
});
})
}
Can be shortened to:
getSeedConfig(){
const doc = ref(this.db, 'config/seed');
return get(doc).then((snapshot) => {
return snapshot.val(); // 👈 returns null when the snapshot does not exist
})
}
i've get problem in my project code.
I develop website for Online Shop purpose, honestly i'm using template from GitHub for faster production ( My lecture said ). Product working as well but Categories can't working as my expectation.
I'm using Next.js and this first time use FullStack on JavaScript. I'm wanna call my API from MongoDB with Axios and there have categories field within data type Array. This file i haven't change anyword.
Error said :
Cannot read property 'items' of undefined
This my line code inventoryByCategory.js :
function inventoryByCategory (inventory) {
return inventory.reduce((acc, next) => {
const categories = next.categories
categories.forEach(c => {
if (acc[c]) {
acc[c].items.push(next)
} else {
acc[c] = {}
acc[c].items = []
acc[c].items.push(next)
}
})
return acc
}, {})
}
export {
inventoryByCategory
}
This my data fecthing on inventoryProvider.js
import axios from "axios"
async function fetchInventory() {
const inventory = await axios.get('http://localhost:3000/api/inventory')
.then((response) => response.data.data)
return Promise.resolve(inventory)
}
export {
fetchInventory
}
And this my error show up in inventoryForCategory.js :
import { fetchInventory } from './inventoryProvider'
import { inventoryByCategory } from './inventoryByCategory'
async function inventoryForCategory (category) {
const inventory = await fetchInventory()
const byCategory = inventoryByCategory(inventory)
return byCategory[category].items
}
export default inventoryForCategory
I think this enough information for you, thanks in advance :)
This is my gatsby-node.js file. I am attempting to get my gatsby program to dynamically create pages for each user in my api with the path being node.example. I'm currently running a local dev environment and I am getting my data from a local json server. It appears that a page is only being created for the users that I manually place a "path" field with "/example" in their corresponding json element. Also, in graphiQL, it is only returning data for the users that have an "ID" field when I call allRestApiEmployees. Any idea on how to fix this?
const path = require("path")
exports.createPages = ({ actions, graphql }) => {
const { createPage } = actions
//this is going to be referencing fields.js - not that specific node
const profileTemplate = path.resolve("src/components/layout.js")
//query to return user data
return graphql(`
{
allRestApiEmployees {
edges {
node {
example
}
}
}
}
`).then(res => {
if (res.errors) {
return Promise.reject(res.errors)
}
res.data.allRestApiEmployees.edges.forEach(({ node }) => {
var path = "/" + node.example
console.log(node.example)
createPage({
path,
component: profileTemplate,
})
})
})
}
I am following the how to graphql tutorial where I am setting up a simple graphql server.
index.js
const { GraphQLServer } = require('graphql-yoga');
// 1
let links = [{
id: 'link-0',
url: 'www.howtographql.com',
description: 'Fullstack tutorial for GraphQL'
}];
const resolvers = {
Query: {
info: () => `This is the API of a Hackernews Clone`,
// 2
feed: () => links,
},
// 3
Link: {
id: (parent) => parent.id,
description: (parent) => parent.description,
url: (parent) => parent.url,
}
};
// 3
const server = new GraphQLServer({
typeDefs:'./schema.graphql',
resolvers,
});
server.start(() => console.log(`Server is running on http://localhost:4000`));
As you can see, I am referencing my schema file when creating the GraphQLServer. When I run the server, however, I am getting the following error:
/Users/BorisGrunwald/Desktop/programmering/Javascript/GraphQL/hackernews-node/node_modules/graphql-yoga/dist/index.js:418
throw new Error("No schema found for path: " + schemaPath);
^
My file structure:
Can anyone spot the error?
You gave the path ./schema.graphql which makes node look for the file in the directory where you run it instead of the correct location which is 'src/schema.graphql'.
So you need to change the path to:
//...
typeDefs: 'src/schema.graphql',
//...