Setup Contentful Javascript SDK in React Native - reactjs

I'm trying to implement Contentful Javascript SDK on a React Native project (without Expo).
This is the code:
const {createClient} = require('contentful/dist/contentful.browser.min.js')
useEffect(() => {
getContentfulData()
}, [])
const getContentfulData = async () => {
var client = createClient({
adapter: (config) => {
config.adapter = null
return fetch(config)
},
space: '---',
accessToken: '---',
})
await client
.getEntries()
.then((entries) => {
console.log(entries)
})
.catch((error) => {
console.log(error)
})
}
But I'm getting TypeError: Network request failed over and over again.
Any ideas?

const { createClient } = require('contentful/dist/contentful.browser.min.js')
const client = createClient({
space: '*********',
accessToken: '****************************************',
})
client
.getEntries({
content_type: 'trendingBlogs',
})
.then(entry => console.log(entry))
.catch(err => console.log(err))
your missing the getEntries parameters.
i.e
{
content_type: 'trendingBlogs',
}

Related

firebase react cloud messaging push notification [duplicate]

I was working on a project using Firebase cloud messaging react. I was sending this to my server, but it doesn't work. Surely I have tried, but I don't know what's wrong again.
Below is the code.
Here it sends a POST request to Firebase, and it should send a notification to the user.
async function sendNotification(id, userMessage) {
const headers = {
'Authorization': `key=${code}`,
'Content-Type': 'application/json'
}
const message = {
'to': `${id}`,
'content_available': true,
'apns_priority': 5,
'notification': {
body: `${userMessage}`
},
const url = 'https://fcm.googleapis.com/fcm/send'
//console.log(code)
await axios.post(url, message, {
headers: headers
})
}
const sendMessageToServer = async (e) => {
//e.preventDefault();
toggle()
const docRe = doc(database, "help", mailer);
const data = {
email: user.email,
user: newMessage,
}
//console.log(data, 'not clear')
setNewMessage('')
//console.log(data, newMessage, 'cleared')
setShow(false)
if(newMessage === '') {
}
else {
const docRef = doc(database, "users", mailer);
await updateDoc(docRe, {
msg: arrayUnion(data)
})
.then(() => {
async function p() {
const id = await getDoc(docRef)
//console.log(id.data())
sendNotification(id.data().notice, `Admin : ${data.user}`)
}
p()
})
}
Sometimes it sends to my localhost because I tested there, but it doesn't work on my Netlify app. Secondly, I noticed that it keeps generating the same token for each user, but that's not the issue, but if you can help in both I would be grateful.
export default function Dashboard() {
async function callToken() {
await getToken(messaging, {vapidKey: process.env.NOTIFICATION})
.then((code) => {
//console.log(code)
async function docRef() {
const dc = doc(database, "users", auth.currentUser.email);
await updateDoc(dc, {
notice: code
});
}
docRef()
})
}
async function requestPermission() {
await Notification.requestPermission()
.then((permission) => {
if (permission === 'granted') {
console.log('Notification permission granted.')
callToken()
}
})
}
const goTo = useNavigate();
useEffect(() => {
onAuthStateChanged(auth, (data) => {
if(!data) {
goTo('/login')
}
else {
currentBalance();
requestPermission()
}
})
})
}
Please know I imported all required modules.

ReactJS axios post: returns null when it comes/goes from/to backend

I am stuck on this problem for 2 days. I am sending POSTrequest from frontend to the backend (and other GET requests too but the problem is only with POST). However, when my data goes to the backend it does not post anything to the rest api even though response is 200 OK. That's why when in response it should have given the posted data, it can't find it and gives null. This is my POST code in backend index.js:
const { response, request } = require('express');
require('dotenv').config()
const express = require('express');
const morgan = require('morgan');
const Contact = require('./models/contact.cjs');
const cors = require('cors')
const app = express();
app.use(express.json())
app.use(express.static('build'))
app.use(cors())
morgan.token('body', req => {
return JSON.stringify(req.body)
})
app.use(morgan(':method :url :status :res[content-length] - :response-time ms :body'));
const generateId = () => {
const randNum = Math.floor(Math.random() * 5000)
return randNum;
}
app.post('/api/persons', (req, res) => {
const body = req.body
console.log(body)
if (!body.name || !body.number) {
return res.status(400).json({
error: "missing data"
})
} else if (Contact.find({name: body.name})) {
Contact.findOneAndUpdate({name: body.name}, {$set: {number: body.number}}, {new:true})
.then(updatedContacts =>
res.json(updatedContacts)
)
.catch(err => console.log(err))
} else {
const contact = Contact({
id: generateId(),
name: body.name,
number: body.number,
date: new Date()
})
contact.save()
.then(savedContact => {
console.log(savedContact)
res.json(savedContact)
})
.catch(err => {
console.log(err)
})
}
})
const PORT = process.env.PORT
app.listen(PORT, () => {
console.log(`Server is working on ${PORT}`)
})
and this is how my frontend sends data to backend: contacts.js:
const create = (newObject) => {
const readyToPost = {
method: 'post',
url: `${baseUrl}`,
data: newObject,
headers: {'Content-Type': 'application/json'},
json: true
}
const request = axios(readyToPost)
return request.then(response => {
console.log(response.data)
return response.data
})
.catch(err => {
console.log(err)
})
}
And this is my react app's frontend.
Any ideas about why my data becomes null?
Any help would be appreciated!
Due to the synchronous nature of your code, the condition Contact.find({name: body.name}) was always returning the Query object which is true due to which the else if block was getting executed even when there was no such document. After entering the else if block, since there was no match, so findOneAndUpdate() was returning null.
Use findOne() instead of find(). find() returns a cursor which is empty but true whereas findOne() returns the first document matched (if matched) or else it will return null (if not matched).
// index.js (Backend)
app.post("/api/persons", async (req, res) => {
const body = req.body;
if (!body.name || !body.number) {
return res.status(400).json({
error: "missing data",
});
}
// Using findOne() instead of find(). Returns null if record not found.
const existing = await Contact.findOne({ name: body.name });
if (existing) {
Contact.findOneAndUpdate(
{ name: body.name },
{ $set: { number: body.number } },
{ new: true }
)
.then((updatedContacts) => {
console.log(updatedContacts);
res.status(200).json(updatedContacts);
})
.catch((err) => console.log(err));
} else {
const contact = Contact({
id: generateId(),
name: body.name,
number: body.number,
date: new Date(),
});
contact
.save()
.then((savedContact) => {
console.log(savedContact);
res.status(201).json(savedContact);
})
.catch((err) => {
console.log(err);
});
}
});

Nextjs - Get protected reuqests from getServerSideProps

I am working with next js app. For backend I use laravel with sanctum autentication. I want to implement credential authentication (username, password) using laravel sanctum and nextjs SPA app. All these working with client side. But I can not access to protected request in getServerSideProps. It requires crsf token.
pages/login.js
import React, { useState } from 'react';
import api from '#/util/api';
import { logIn } from '#/util/auth';
const LogInPage = () => {
const [formInput, setFormInput] = useState({ username: '', password: '' });
const signIn = (e) => {
e.preventDefault();
api()
.get('/sanctum/csrf-cookie')
.then(() => {
api()
.post('/api/login', formInput)
.then((response) => {
if (response.data.error) {
console.log(response.data.error);
} else {
router.push('/')
}
});
});
};
pages/index.js (protected route)
const Home = ({ user }) => {
const [users, setUsers] = useState([]);
useEffect(() => {
api()
.get('/api/users')
.then((response) => {
setUsers(response.data);
});
}, []);
}
Question: How to do it with getServerSideProps? Or how to use this implementation using NextAuth.js? Or maybe need bridge between client to server
export async function getServerSideProps() {
let users = [];
api()
.get('/api/users')
.then((response) => {
users = response.data;
})
.catch((error) => {
console.error(error);
});
return {
props: { users },
};
}
'/api/users' route is protected, requires authentication, so it responds 401 unauthorized

How to make Async Await Function in React Native?

I want to create a function that is about uploading photo to Firebase Storage with react-native-fetch-blob. I'm using Redux and you can find action functions below:
My problem is that uploadImage function is not running like asynchronous. Firebase function is running before uploadImage, so application give me an error.
I think i can't make a asynchronous function. How can i fix it ?
uploadImage() function:
const uploadImage = async (imageSource, whereToUpload) => {
let imageURL = '';
const mime = 'image/jpg';
const { Blob } = RNFetchBlob.polyfill;
const { fs } = RNFetchBlob;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
console.log('URI =>', imageSource.uri);
let imgUri = imageSource.uri;
let uploadBlob = null;
const imageRef = firebase.storage().ref(whereToUpload + '/' + imageSource.fileName);
const uploadUri = Platform.OS === 'ios' ? imgUri.replace('file://', '') : imgUri;
await fs.readFile(uploadUri, 'base64')
.then((data) => Blob.build(data, { type: `${mime};BASE64` }))
.then((blob) => {
uploadBlob = blob;
return imageRef.put(blob, { contentType: mime });
})
.then(() => {
uploadBlob.close();
// eslint-disable-next-line no-return-assign
return imageURL = imageRef.getDownloadURL();
})
.catch((error) => {
console.log(error);
});
return imageURL;
};
and the main action is:
export const addProjectGroup = (
myUser,
groupName,
groupDescription,
groupProfilePic,
) => dispatch => {
const groupProfileFinalPic = async () => {
let finalGroupPicture = { landscape: '' };
if (_.isEmpty(groupProfilePic.src)) {
await uploadImage(groupProfilePic, 'groupPictures').then((imageURL) => {
console.log('İŞLEM TAMAM!');
console.log('SELECTED IMAGE URL =>', imageURL);
finalGroupPicture.landscape = imageURL;
});
} else {
finalGroupPicture.landscape = groupProfilePic.src.landscape;
}
return finalGroupPicture;
};
console.log("final group profile pic =>", groupProfileFinalPic());
// Önce grubu yaratalım..
// eslint-disable-next-line prefer-destructuring
const key = firebase
.database()
.ref()
.child('groups')
.push().key;
firebase
.database()
.ref('/groups/' + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid,
},
groupName,
groupDescription,
groupProfilePic: groupProfileFinalPic(),
projects: '',
})
.then(() => {
console.log('Groups oluşturuldu.');
})
.catch(e => {
Alert.alert('Hata', 'Beklenmedik bir hata meydana geldi.');
console.log(e.message);
});
dispatch({
type: ADD_PROJECT_GROUP,
});
};
You are not awaiting groupProfileFinalPic(). This should be done before creating the action you want to dispatch.
groupProfileFinalPic().then(groupProfilePic => {
return firebase
.database()
.ref("/groups/" + key)
.set({
admin: {
email: myUser.email,
name: myUser.name,
uid: myUser.uid
},
groupName,
groupDescription,
groupProfilePic,
projects: ""
})
.then(() => {
console.log("Groups oluşturuldu.");
})
.catch(e => {
Alert.alert("Hata", "Beklenmedik bir hata meydana geldi.");
console.log(e.message);
});
});
I have no clue what the last dispatch is for, you might want to do that in one of the callbacks. Your code is to verbose for an SO question, but I hope this helps anyways.
You are using both await and then on the same call. To use await, you can arrange it something like
const uploadImage = async (imageSource, whereToUpload) => {
...
try {
let data = await RNFS.fs.readFile(uploadUri, 'base64')
let uploadBlob = await Blob.build(data, { type: `${mime};BASE64` }))
...etc...
return finalResult
catch (e) {
// handle error
}
}

TypeError: http is not a function in Jest framework

I am using React.js as my JavaScript framework, where I have installed Jest and using pact (CDC) for unit test cases and while I run the command npm run test the spec.js file is failing and throwing an error like this
TypeError: http is not a function
This is criteria-managementcomponent.spec.js file
const path = require('path')
const pact = require('pact')
const API_PORT = process.env.API_PORT || 9123
const {
fetchProviderData, getCriteriaManagementComponent, criteriaManagementComponent
} = require('../client')
// Configure and import consumer API
// Note that we update the API endpoint to point at the Mock Service
const LOG_LEVEL = process.env.LOG_LEVEL || 'WARN'
const provider = pact({
consumer: 'Web Login',
provider: 'Web API',
port: API_PORT,
log: path.resolve(process.cwd(), 'logs', 'pact.log'),
dir: path.resolve(process.cwd(), 'pacts'),
logLevel: LOG_LEVEL,
spec: 2
})
describe('Started Testing Pact', () => {
beforeEach((done) => {
return provider.setup().then(() => done());
});
afterEach((done) => {
return provider.finalize().then(() => done())
})
describe('criteriaManagement', () => {
beforeEach(() => {
let criteriaManagement = {
uponReceiving: 'wrong criteriaManagement',
state: 'Code OK',
withRequest: {
method: 'GET',
path: '/api/criteria',
},
willRespondWith: {
status: 200,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
body: {
code: "string",
context: {},
message: "string",
payload: [
{
country: "string",
createdBy: "string",
displayOrder: 0,
id: "string",
lastModifiedBy: "string",
name: "string",
translations: {},
warehouse: "string"
}
]
}
}
};
return provider.addInteraction(criteriaManagement)
})
afterEach(() => {
return provider.verify()
})
it('Login test', done => {
criteriaManagementComponent().then((res) => {
expect(res.code).not.toBeNull();
expect(res.context).toBeDefined();
expect(res.message).not.toBeNull();
expect(res.payload.country).not.toBeNull();
expect(res.payload.createdBy).not.toBeNull();
expect(res.payload.displayOrder).toBe(0);
expect(res.payload.id).not.toBeNull();
expect(res.payload.lastModifiedBy).not.toBeNull();
expect(res.payload.translations).toBeDefined();
expect(res.payload.name).not.toBeNull();
expect(res.payload.warehouse).not.toBeNull();
});
done();
})
});
})
This is client.js file for criteria-managementcomponent.spec.js file
const request = require('superagent')
const API_HOST = process.env.API_HOST || 'http://localhost'
const API_PORT = process.env.API_PORT || 9123
const API_ENDPOINT = `${API_HOST}:${API_PORT}`
// Fetch provider data
const fetchProviderData = (submissionDate) => {
return request
.get(`${API_ENDPOINT}/provider`)
.query({ validDate: submissionDate })
.then((res) => {
console.log("Response :: ", res.body);
return {
count: 100 / res.body.count,
date: res.body.date
}
})
}
const getCriteriaManagementComponent = (accessToken, expiresIn) => {
return request
.post(`${API_ENDPOINT}/api/criteria`)
.then((res) => {
return {
code : res.body.code
}
})
}
const criteriaManagementComponent = () => {
// const request = require('request')
console.log("End Point =========> ", `${API_ENDPOINT}/api/criteria`)
return request.get(`${API_ENDPOINT}/api/criteria`).then((res) => {
return {
code : res.body.code,
context:res.body.context,
message:res.body.message,
payload:res.body.payload,
profile:res.body.payload.profile,
successful : res.body.successful
}
})
};
module.exports = {
fetchProviderData, getCriteriaManagementComponent, criteriaManagementComponent
}
It's hard to know where things are going wrong without a line number in the stack trace, however one thing is for certain - you're using a very old version of pact.
You should be using #pact-foundation/pact now.
As for the http issue, is it possible you have any mocks setup that are interfering? The issue seems unrelated to pact.
Lastly, if you could provide a reproducible github repo that others could download and run, you could probably get even better help.

Resources