React Babel/Jest initial setup - reactjs

I'm currently trying to set up Jest in my React project. I have created a simple snapshot test for App.js. I heard that you cannot run Jest without Babel so I used npm i babel-jest to install them both at the same time. I feel like I have done everything the normal tutorials have asked me to do. However, when I run `npm run test' I get the following error message:
PS C:\XXXXXXXXXXX\git\react-project\client> npm run test
> react-project#0.1.0 test C:\XXXXXXXXXXXX\git\react-project\client
> jest
FAIL src/App.test.js
● Test suite failed to run
SyntaxError: C:\XXXXXXXXXX\git\react-project\client\src\App.test.js: Support for the experimental syntax 'jsx' isn't currently enabled (6:32):
4 |
5 | it ('renders correctly', () => {
> 6 | const tree = renderer.create(<App />).toJSON();
| ^
7 | expect(tree).toMatchSnapshot();
8 | });
Add #babel/preset-react (https://git.io/JfeDR) to the 'presets' section of your Babel config to enable transformation.
If you want to leave it as-is, add #babel/plugin-syntax-jsx (https://git.io/vb4yA) to the 'plugins' section to enable parsing.
at Parser._raise (node_modules/#babel/parser/src/parser/error.js:60:45)
at Parser.raiseWithData (node_modules/#babel/parser/src/parser/error.js:55:17)
at Parser.expectOnePlugin (node_modules/#babel/parser/src/parser/util.js:157:18)
at Parser.parseExprAtom (node_modules/#babel/parser/src/parser/expression.js:1180:18)
at Parser.parseExprSubscripts (node_modules/#babel/parser/src/parser/expression.js:563:23)
at Parser.parseUpdate (node_modules/#babel/parser/src/parser/expression.js:543:21)
at Parser.parseMaybeUnary (node_modules/#babel/parser/src/parser/expression.js:527:17)
at Parser.parseExprOps (node_modules/#babel/parser/src/parser/expression.js:343:23)
at Parser.parseMaybeConditional (node_modules/#babel/parser/src/parser/expression.js:308:23)
at Parser.parseMaybeAssign (node_modules/#babel/parser/src/parser/expression.js:263:21)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 4.303 s
Ran all test suites.
(node:15304) ExperimentalWarning: The fs.promises API is experimental
I feel like the solution is in this error message but I can really understand what they are asking me to do here. Any help would be great! Let me know if you need any more information!
react-project\package.json
{
"name": "react-project",
"version": "1.0.0",
"scripts": {
"client": "cd client && yarn start",
"server": "nodemon server.js"
},
"dependencies": {
"body-parser": "^1.18.3",
"express": "^4.16.4"
},
"devDependencies": {
"concurrently": "^4.0.1",
"nodemon": "^2.0.4"
}
}
react-project\server\server.js
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
const port = process.env.PORT || 5000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get('/api/hello', (req, res) => {
res.send({ express: 'Helo From Express' });
});
app.post('/api/world', (req, res) => {
console.log(req.body);
res.send(
`I received your POST request. This is what you sent me: ${req.body.post}`,
);
});
app.listen(port, () => console.log(`Listening on port ${port}`));
react-project\client\App.js
import React from 'react';
import './App.css';
function App() {
return (
<div className="App">
Hello
</div>
);
}
export default App;
react-project\client\App.test.js
import React from 'react';
import { renderer } from "#testing-library/react";
import App from './App';
it ('renders correctly', () => {
const tree = renderer.create(<App />).toJSON();
expect(tree).toMatchSnapshot();
});
react-project\client\package.json
{
"name": "react-project",
"version": "0.1.0",
"private": true,
"dependencies": {
"babel-jest": "^26.3.0",
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-scripts": "3.4.3"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "jest",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"#babel/core": "^7.11.6",
"#babel/node": "^7.10.5",
"#babel/plugin-transform-react-jsx": "^7.10.4",
"#babel/preset-env": "^7.11.5",
"jest": "^26.4.2",
"nodemon": "^2.0.4"
}
}

Related

Electron app not running after building with electron-forge [duplicate]

Here is my package.js file
{
"name": "cabed",
"version": "0.1.0",
"private": false,
"dependencies": {
"#testing-library/jest-dom": "^5.16.5",
"#testing-library/react": "^13.4.0",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"electron-forge": "^5.2.4",
"electron-is-dev": "^2.0.0",
"electron-packager": "^17.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"main": "public/electron.js",
"homepage": "./",
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject",
"dev": "concurrently -k \"cross-env BROWSER=none npm start\" \"npm:electron\"",
"electron": "wait-on tcp:3000 && electron .",
"eb": "electron-packager C:/Users/user/cabed cddf --platform=win32 --arch=x64"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"concurrently": "^7.6.0",
"cross-env": "^7.0.3",
"electron": "^22.1.0",
"wait-on": "^7.0.1"
},
"config": {
"forge": {
"packagerConfig": {},
"makers": [
{
"name": "#electron-forge/maker-squirrel",
"config": {
"name": "stock_trading_app"
}
},
{
"name": "#electron-forge/maker-zip",
"platforms": [
"darwin",
"linux",
"win32"
]
},
{
"name": "#electron-forge/maker-deb",
"config": {}
},
{
"name": "#electron-forge/maker-rpm",
"config": {}
}
]
}
}
}
The generated exe with electron builder which i ran with
npm run eb
the exe generated by code above
does not render the react app inside the opened windows app.
Here is my app js
import logo from './logo.svg';
import './App.css';
function App() {
return (
<div style={{justifyContent:'center',alignContent:'center',alignItems:'center'}}>
<div className="App">
<img src={logo} className="App-logo" alt="logo" />
<p>
Sasdsad
</p>
<p>
Sasdsad
</p>
</div></div>
);
}
export default App;
my electron.js looks like this under public directory.
const path = require('path');
const { app, BrowserWindow } = require('electron');
const isDev = require('electron-is-dev');
function createWindow() {
// Create the browser window.
const win = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
nodeIntegration: true,
},
});
// and load the index.html of the app.
// win.loadFile("index.html");
win.loadURL(
isDev
? 'http://localhost:3000'
: `file://${path.join(__dirname, "./index.html")}`
);
// Open the DevTools.
if (isDev) {
win.webContents.openDevTools({ mode: 'detach' });
}
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.whenReady().then(createWindow);
// Quit when all windows are closed, except on macOS. There, it's common
// for applications and their menu bar to stay active until the user quits
// explicitly with Cmd + Q.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
When running npm start first, then the exe renders react page inside window.
I need some configuration probably but i could not found it yet.
Since you said it works when you start your server first, I assume you're using the localhost URL both in dev and in prod. When your app is packaged, you should load the file in your window and not the local URL:
const { app } = require("electron");
const windowURL = app.isPackaged
? `file://${path.join(__dirname, "./index.html")}`
: "http://localhost:3000/";
mainWindow.loadURL(windowURL);
The path when your app is packaged might be different depending on your file structure and your build/package configurations. Also, don't forget to add "homepage": "./" on your package.json or you may get a blank page.

Deploying React, Express project to Heroku

I have created a small React Express app and am struggling with deploying it to Heroku.
So far I have organised the client and server into separate folders.
Previously I had the contents of server in the projects root and client as its own folder accessed with a path.join however this didn't serve any of the build files so I opted to separate the folders.
Now with two folders I use a root package.json to install all dependencies and get both sides running.
{
"name": "project",
"version": "1.0.0",
"main": "",
"scripts": {
"start": "npm start --prefix server",
"install-client": "cd client && npm install && npm run build && cd ..",
"install-server": "cd server && npm install && cd .. ",
"heroku-postbuild": "npm run install-client && npm run install-server"
}
}
This works with my other folders in serving the back-end however there is no front-end at all. I'm wondering if there is a solution to this problem specifically or even a better way to deploy a full stack project in the same dyno.
This is my currently result on my Heroku app:
Heroku app result
And here any additional relevant files:
Main server file
const express = require('express');
const path = require('path');
const cors = require('cors');
const db = require('./config/db');
const app = express();
const PORT = process.env.PORT || 8080;
//Dependencies
app.use(express.json());
app.use(cors());
//Select all rows from table
app.get('/api/get', (req, res) => {
const selectAll = 'SELECT * FROM plant_data';
db.query(selectAll, (err, rows) => {
if (err) throw err;
res.send(rows);
});
});
//Insert into database
app.post('/api/insert', (req, res) => {
const row = req.body.row;
const insert = "INSERT INTO plant_data (test) VALUES (?)";
db.query(insert, [row], (err, rows) => {
if (err) throw err;
console.log("inserted: " + row);
});
});
//Server port
app.listen(process.env.PORT || PORT, () => {
console.log('Server started on port ' + PORT);
});
Main client file
import React, {useState, useEffect} from "react";
import axios from "axios";
export default function Index() {
const [data, setData] = useState('');
const [rows, setRows] = useState([]);
useEffect(() => {
axios.get('/api/get')
.then(res => {
setRows(res.data);
}).catch(err => {
console.log(err);
});
});
//Connects front-end submit to backend db
const insertRow = () => {
axios.post('/api/insert', {
row: data
});
};
return (
<>
<h1>Body</h1>
<input type="text" onChange={(e) => {
setData(e.target.value);
}} />
<button onClick={insertRow}>Submit</button>
{rows.map((row) => {
return <p>{row.test}</p>
})}
</>
);
};
Server package file:
{
"name": "server",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js",
"heroku-postbuild": "npm install --prefix client && npm run build --prefix client"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.20.0",
"cors": "^2.8.5",
"express": "^4.18.1",
"mysql": "^2.18.1",
"nodemon": "^2.0.19"
}
}
Client package file:
{
"name": "client",
"version": "0.1.0",
"private": true,
"dependencies": {
"#emotion/react": "^11.8.2",
"#material-ui/core": "^4.12.3",
"#mui/material": "^5.5.3",
"#testing-library/jest-dom": "^5.16.2",
"#testing-library/react": "^12.1.4",
"#testing-library/user-event": "^13.5.0",
"axios": "^0.27.2",
"hamburger-react": "^2.4.1",
"node-sass": "^7.0.1",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-helmet": "^6.1.0",
"react-router-dom": "^6.2.2",
"react-scripts": "5.0.0",
"styled-components": "^5.3.5",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}

how to deploy app to heroku and proxy API request

Can you help me find what's wrong when I try to deploy my fullstack app to heroku.
where can I find the solution to make my http requests work ?
I have tried :
adding a proxy in the package.json
using npm http-proxy-middleware
Nothing seems to work ??
This is my index.js
const express = require("express");
const bodyParser = require("body-parser");
require('dotenv').config();
const app = express();
const { createProxyMiddleware } = require("http-proxy-middleware");
const path = require("path");
const routes = express.Router()
const { getAll, getSingle, postArticle, postComment, postVote } = require("./routes");
const cors = require("cors");
app.use(cors());
app.use('/articles', routes);
routes.use("/", getAll);
routes.use("/:id", getSingle)
routes.use("/:id/upvote", postVote);
routes.use("/insert", postArticle);
// create another collection comment
routes.use("/:id/add-comment", postComment);
//middleware
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// Step 1:
app.use(express.static(path.resolve(__dirname, "./build")));
// Step 2:
app.get('*', function(req, res) {
res.sendFile(path.join(__dirname, './build/index.html'));
});
app.listen(4000, () => {
console.log(`server running on port 4000`);
});
and, package.json
{
"name": "app",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^13.1.1",
"#testing-library/user-event": "^13.5.0",
"react": "^18.0.0",
"react-dom": "^18.0.0",
"react-scripts": "5.0.1",
"web-vitals": "^2.1.4"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
404 - NotFound
To make it simple, each request is basically followed by url/route/end-point
https://deploy-mern-2084.herokuapp.com/articles/somthing_else
"something_else" should be replaced with one of your endpoint from your nodejs code at your route file
Please, make sure that your node js is not running at the same url with you react js code

Cypress returns "browserslist" error in Create React App?

I've got a very simple Create React App that I am trying to implement Cypress with. I initially had a different but related error that I was able to overcome. I'm not entirely sure why I would be given this type of error considering I do have the default "browserslist" key in my package.json file.
package.json
{
"name": "cypress_test",
"version": "0.1.0",
"private": true,
"engines": {
"node": "16.13.1",
"npm": "8.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"cypress": "cypress open",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"dependencies": {
"#cypress/react": "^5.12.4",
"#cypress/webpack-dev-server": "^1.8.4",
"#emotion/react": "^11.9.0",
"#emotion/styled": "^11.8.1",
"#fontsource/roboto": "^4.5.5",
"#mui/icons-material": "^5.6.2",
"#mui/material": "^5.6.3",
"#mui/styled-engine-sc": "^5.6.1",
"#testing-library/jest-dom": "^5.16.4",
"#testing-library/react": "^12.1.5",
"#testing-library/user-event": "^13.5.0",
"browserslist": "^4.6.3",
"cypress": "^9.6.0",
"react": "^17.0.2",
"react-dom": "^17.0.2",
"react-scripts": "5.0.1",
"sass": "^1.51.0",
"styled-components": "^5.3.5",
"web-vitals": "^2.1.4"
},
"devDependencies": {
"#babel/core": "^7.17.9",
"#babel/preset-env": "^7.16.11",
"#cypress/webpack-preprocessor": "^5.11.1",
"babel-loader": "^8.2.5",
"eslint-plugin-cypress": "^2.12.1",
"html-webpack-plugin": "^4.5.2",
"webpack": "^5.72.0"
},
"eslintConfig": {
"extends": [
"react-app",
"react-app/jest"
]
},
"overrides": [
{
"extends": [
"plugin:cypress/recommended"
],
"files": [
"cypress/**/*.js"
]
}
],
"resolutions": {
"#mui/styled-engine": "npm:#mui/styled-engine-sc#latest"
},
"jest": {
"coveragePathIgnorePatterns": [
"<rootDir>/cypress/"
]
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
When I initially installed CRA, it used the latest version of React 18, but apparently Cypress doesn't have support for 18 yet so I downgraded React to 17. I'm wondering if there are some sort of package mismatches that I'm unaware of and aren't receiving specific errors for. As a note though, the app runs fine in the browser. Here are the other related files:
/cypress/plugins/index.js:
const findWebpack = require('find-webpack')
const webpackPreprocessor = require('#cypress/webpack-preprocessor');
const injectDevServer = require('#cypress/react/plugins/react-scripts');
module.exports = (on, config) => {
const webpackOptions = findWebpack.getWebpackOptions();
if (!webpackOptions) {
throw new Error('Could not find Webpack in this project');
}
const cleanOptions = { reactScripts: true };
findWebpack.cleanForCypress(cleanOptions, webpackOptions);
const options = {
webpackOptions,
watchOptions: {},
};
on('file:preprocessor', webpackPreprocessor(options));
injectDevServer(on, config);
return config;
};
App.spec.js:
import React from 'react';
import data from '../fixtures/data.json';
import App from '../../src/App.jsx';
describe('Test search functionality', () => {
beforeEach(() => {
cy.mount(<App />);
});
it('renders new fact when search is performed', () => {
cy.visit('http://localhost:3001')
// Type in search input
cy.get('input').type('Test');
// Click on search button
cy.get('.submit-btn').click();
// Intercept the request and return the mock data
cy
.intercept({
method: 'GET',
url: `${process.env.REACT_APP_API_ENDPOINT}/jokes/search?query=Test`
}, {
fixture: data.result[1]
})
.as('fetchFact');
// cy.wait(['#fetchFact']);
cy.get('p.copy').should('contain', data.result[1].value);
})
});
cypress.json:
{
"baseUrl": "http://localhost:3001",
"videos": false,
"component": {
"testFiles": "**/*.cy.{js,ts,jsx,tsx}",
"componentFolder": "src"
}
}
Cypress error:
Error: No browserslist config found to handle the 'browserslist' target.
See https://github.com/browserslist/browserslist#queries for possible ways to provide a config.
The recommended way is to add a 'browserslist' key to your package.json and list supported browsers (resp. node.js versions).
You can also more options via the 'target' option: 'browserslist' / 'browserslist:env' / 'browserslist:query' / 'browserslist:path-to-config' / 'browserslist:path-to-config:env'
at TARGETS.web (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:93:11)
at getTargetProperties (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:296:19)
at /Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:342:20
at Array.map (<anonymous>)
at getTargetsProperties (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/target.js:342:11)
at applyWebpackOptionsDefaults (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/config/defaults.js:142:6)
at createCompiler (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:77:2)
at create (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:134:16)
at webpack (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/webpack.js:158:32)
at f (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/webpack/lib/index.js:63:16)
at Object.handler (/Users/jimmiejackson/Documents/repositories/cypress_test/node_modules/#cypress/webpack-preprocessor/dist/index.js:148:24)
at invoke (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:22:16)
at /Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:45:14
at tryCatcher (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/node_modules/bluebird/js/release/util.js:16:23)
at Function.Promise.attempt.Promise.try (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/node_modules/bluebird/js/release/method.js:39:29)
at Object.wrapChildPromise (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:44:23)
at Object.wrap (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/preprocessor.js:28:8)
at execute (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:123:27)
at EventEmitter.<anonymous> (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/child/run_plugins.js:213:5)
at EventEmitter.emit (node:events:390:28)
at process.<anonymous> (/Users/jimmiejackson/Library/Caches/Cypress/9.6.0/Cypress.app/Contents/Resources/app/packages/server/lib/plugins/util.js:19:22)
at process.emit (node:events:390:28)

'react' - After run npm start it gives./src/contentful.js Module not found: Can't resolve 'contenful' in 'C:\Users\..\my-blog\src'

I ran npm install, got the node modules and packages but when I run npm start I get this error:
./src/contentful.js
Module not found: Can't resolve 'contenful' in 'C:\Users\Dannis\my-blog\src'
I tried to remove package-json.lock, run npm install and npm start afterward and still got the same block. (Also tried npm update, npm install and npm start, still same bug).
This is how my package.json looks like:
{
"name": "my-blog",
"version": "0.1.0",
"private": true,
"dependencies": {
"#testing-library/jest-dom": "^4.2.4",
"#testing-library/react": "^9.4.0",
"#testing-library/user-event": "^7.2.1",
"contentful": "^7.13.1",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-scripts": "3.4.0",
"touch": "^3.1.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
I tried to install react-router-dom, react-markdown and history and I get this error:
Cannot read property 'match' of undefined.
Any ideas?
#user8555937 i ran npm version got this:
{
'my-blog': '0.1.0',
npm: '6.13.7',
ares: '1.15.0',
brotli: '1.0.7',
cldr: '35.1',
http_parser: '2.9.3',
icu: '64.2',
llhttp: '2.0.4',
modules: '72',
napi: '5',
nghttp2: '1.40.0',
node: '12.16.0',
openssl: '1.1.1d',
tz: '2019c',
unicode: '12.1',
uv: '1.34.0',
v8: '7.8.279.23-node.31',
zlib: '1.2.11'
}
#PedroMutter code for ./src/contentful.js:
const client = require('contentful').createClient({
space: 'urer2vtwz5u1',
accessToken: 'H31gCjOrReWAIbKiBWwBCtYF0_iw5kSVjZxh1FyHzNk'
})
const getBlogPosts = () => client.getEntries().then(response => response.items)
const getSinglePost = slug =>
client
.getEntries({
'fields.slug': slug,
content_type: 'blogPost'
})
.then(response => response.items)
export { getBlogPosts, getSinglePost }
UPDATE: just ran an npm update and now I get:
./src/contentful.js
Line 1:16: 'contentful' is not defined no-undef
As you are running it in a browser, try to import the contentful library using es6 import, you are mixing it with Commonjs:
import * as contentful from 'contentful';
const client = contentful.createClient({
space: 'urer2vtwz5u1',
accessToken: 'H31gCjOrReWAIbKiBWwBCtYF0_iw5kSVjZxh1FyHzNk'
})
const getBlogPosts = () => client.getEntries().then(response => response.items)
const getSinglePost = slug =>
client
.getEntries({
'fields.slug': slug,
content_type: 'blogPost'
})
.then(response => response.items)
export { getBlogPosts, getSinglePost }

Resources