Finding effective way to fetch data from mongo db - reactjs

I want to fetch data from mongodb by using document property similarly like findById() method I can fetch with query but I want to display data on another page
This is my api code for fetching data
const User = require("../models/User");
const Image = require("../models/Image");
const addImage = async (req, res, next) => {
const newImage = new Image({ userId: req.user.id, ...req.body });
try {
const saveImage = await newImage.save();
res.status(200).json("Image uploaded");
} catch (error) {
next(error);
}
};
// GETPRODUCTBYID :-
const getImage = async (req, res) => {
try {
const image = await Image.findById(req.params.id);
res.status(200).json(image);
} catch (error) {
res.status(500).json(error);
}
};
// GET ALL PRODUCTS :-
const getAllImages = async (req, res) => {
const qNew = req.query.new;
const qCategory = req.query.category;
const qBrand = req.query.brand;
try {
let images;
if (qNew) {
images = await Image.find().sort({ createdAt: -1 }).limit(1);
} else if (qCategory) {
images = await Image.find({
categories: { $in: [qCategory] },
});
}
if (qBrand) {
images = await Image.find({ brand: "Honda" });
} else {
images = await Image.find();
}
res.status(200).json(images);
} catch (error) {
res.status(500).json(error);
}
};
// GET IMAGES BY BRAND :-
const getImagesByBrand = async (req, res) => {
const qBrand = req.query.brand;
try {
const images = await Image.find( {brand: qBrand});
res.status(200).json(images);
} catch (error) {
res.status(500).json(error);
}
};
module.exports = Object.freeze({
addImage,
getImage,
getImagesByBrand,
getAllImages,
});
Structure of document in mongo db
Document
_id
brand
I want to fetch data with brand property and show it on new page it is possible?

Related

Reactjs send json object from client to server(express) not working

I tried to send the json objects from client to the backend(express) and then save it to mongodb. I can see the json objects sent but with "undefined" at the end.
Client side to send the json object :
setCategoryFile(JSON.stringify(Categories))
const saveStmnt = async (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('categoryFilename', categoryFile)
const config = {
headers: {
'content-type': 'application/json'
}
};
try {
await axios.post("http://localhost:3001/statements", formData,
config, {
});
navigate("/");
} catch (error) {
console.log(error);
}
};
code from backend (express):
export const saveStatement = async (req , res , next) => {
// const info = new StatementSchema(req.body)
console.log('CreditCardAnalysis.js : Perform saveStatement')
console.log(req.body.categoryFile)
let data = new Statement ( {
categoryFile : req.body.categoryFile
})
console.log("perform savedSTmnt...save")
try {
const savedStmnt = await data.save();
if (err)
res.end('Error in saving the statement');
else
{
res.status(201).json(savedStmnt)
res.redirect('/')
}
//res.status(200).json(JSON.stringify(savedProduct));
} catch (err) {
res.redirect('/');
res.end();
}
};
Result from backend :
Database Connected...
{
categoryFilename: '[{"description":"GOOGLE","category":"MISC"},{"description":"AMZN","category":"MERCHANDISE"},{"description":"MCDONALD","category":"DINNING"},{"description":"SAFEWAY","category":"GROCERIES"},{"description":"WISH","category":"MERCHANDISE"},{"description":"99 RANCH","category":"GROCERIES"},{"description":"PARKMOBILE","category":"COLLEGE FEE"},{"description":"CITY OF SAN RAMON","category":"TENNIS"},{"description":"FILA","category":"APPAREL"},{"description":"COMCAST","category":"TELECOM"},{"description":"PEETS","category":"COFFEE"}]'
}
undefined

React useEffect gives react-hooks/exhaustive-deps error on publishing

My .net core react web application works fine, except that when I try to publish it gives me the following error:
Occurred while linting C:\.....Fetch.js: 79
Rule: "react-hooks/exhaustive-deps"
This is my code:
const populateTable1Data = async () => {
var response = await axios.get(apiurl + { params: { id: props.id1 } });
var data = await response.data;
setTable1Data(data);
}
const populateTable2Data = async () => {
var response = await axios.get(apiurl + { params: { id: props.id2 } });
var data = await response.data;
setTable2Data(data);
setLoading(false);
}
useEffect(() => {
const load = async () => {
await populateTable1Data();
await populateTable2Data();
setLoading(false)
}
load()
}, []);
Problem is that I have a very similar useEffect inside another component which doesn't give errors though:
const populateTableData = async () => {
const response = await axios.get(apiurl + key);
const data = await response.data;
setTableData(data);
setLoading(false);
}
useEffect(() => {
populateTableData();
}, [])
If anyone has the same problem, I solved by doing this:
const populateTable1Data = async (dataProps) => {
var response = await axios.get(apiurl + { params: { id: dataProps.id1 } });
var data = await response.data;
setTable1Data(data);
}
const populateTable2Data = async (dataProps) => {
var response = await axios.get(apiurl + { params: { id: dataProps.id2 } });
var data = await response.data;
setTable2Data(data);
setLoading(false);
}
useEffect(() => {
const load = async () => {
await populateTable1Data(props);
await populateTable2Data(props);
setLoading(false)
}
load()
}, [props]);
I essentially passed the props on the function call, I don't know why does it have to be this way, I'll leave the answer here in case anyone else needs it while waiting for someone to be kind enought to explain the reason for this.

Dynamic generated sitemap -there are only declared pages on sitemap

I'd like to generate dynamic url fo each slug, but there is an array only with pages which I declared: const pages = ["/", "/about", "/portfolio", "/blog"];
http://localhost:3000/api/my-sitemap. I've installed npm sitemap from https://www.npmjs.com/package/sitemap
my query in ../../lib/data.js
export const getBlogSlugs = async () => {
const endpoint =
"https://api-eu-central-gsagasgasxasasxsaxasxassaster";
const graphQLClient = new GraphQLClient(endpoint);
const query = gql`
{
posts {
slug
}
}
`;
return await graphQLClient.request(query);
};
pages/api/my-sitemap.js
import { getBlogSlugs } from "../../lib/data";
const { SitemapStream, streamToPromise } = require("sitemap");
const { Readable } = require("stream");
export const getStaticProps = async () => {
const { posts } = await getBlogSlugs();
return {
props: {
posts,
},
};
};
export default async (req, res, posts) => {
try {
const links = [];
posts?.map((slug) => {
links.push({
url: `/blog/${slug}`,
changefreq: "daily",
priority: 0.9,
});
});
// Add other pages
const pages = ["/", "/about", "/portfolio", "/blog"];
pages.map((url) => {
links.push({
url,
changefreq: "daily",
priority: 0.9,
});
});
// Create a stream to write to
const stream = new SitemapStream({
hostname: `https://${req.headers.host}`,
});
res.writeHead(200, {
"Content-Type": "application/xml",
});
const xmlString = await streamToPromise(
Readable.from(links).pipe(stream)
).then((data) => data.toString());
res.end(xmlString);
} catch (e) {
console.log(e);
res.send(JSON.stringify(e));
}
};
I added to my robots.txt in pudblic folder:
User-agent: *
Allow: /
Sitemap: http://localhost:3000/api/my-sitemap
What I got is only declared pages
localhost:3000/api/my-sitemap
I tried like this and doesn't work too:
export const getStaticProps = async () => {
const data = await getBlogSlugs();
return {
props: {
posts: data.posts,
},
};
};
export default async (req, res, posts) => {
try {
const links = [];
posts?.map((post) => {
links.push({
url: `/blog/${post.slug}`,
changefreq: "daily",
priority: 0.9,
});
});
You cannot use getStaticProps from an API route.
https://github.com/vercel/next.js/discussions/16068#discussioncomment-703870
You can fetch the data directly inside the API function.
Edit: In my app, I use the API route code below to fetch data from external server
import fetch from "isomorphic-unfetch";
export default async (req, res) => {
try {
const result = await fetch("YOUR_URL");
const posts = await result.json();
//use posts
});
} catch (e) {}
};
For GraphQl may be you can check the example given in vercel site
https://github.com/vercel/next.js/tree/canary/examples/api-routes-graphql

Sending verification email with Firebase and React Native

I am trying to send the validation email upon the account registration, using firebase. The registration is being done successfully but whenever I try to code email verification it gives me an error. Probably because I don't know where to place it. All my firebase methods are on Fire.js, which are the following:
import firebaseKeys from './Config';
import firebase from 'firebase';
require("firebase/firestore");
class Fire {
constructor() {
if (!firebase.apps.length) {
firebase.initializeApp(firebaseKeys);
}
}
addPost = async ({ text, localUri }) => {
const remoteUri = await this.uploadPhotoAsync(localUri, 'photos/${this.uid}/${Date.now()}');
return new Promise((res, rej) => {
this.firestore.collection('posts').add({
text,
uid: this.uid,
timestamp: this.timestamp,
image: remoteUri
})
.then(ref => {
res(ref);
})
.catch(error => {
rej(error);
});
});
}
uploadPhotoAsync = async (uri, filename) => {
return new Promise(async (res, rej) => {
const response = await fetch(uri);
const file = await response.blob();
let upload = firebase
.storage()
.ref(filename)
.put(file);
upload.on(
"state_changed",
snapshot => {},
err => {
rej(err);
},
async () => {
const url = await upload.snapshot.ref.getDownloadURL();
res(url);
}
);
});
}
createUser = async user => {
let remoteUri = null
try {
await firebase.auth().createUserWithEmailAndPassword(user.email, user.password)
//I tried to code it here with user.sendEmailVerification();
let db = this.firestore.collection("users").doc(this.uid)
db.set({
name: user.name,
email: user.email,
avatar: null
})
if (user.avatar) {
remoteUri = await this.uploadPhotoAsync(user.avatar, 'avatars/${this.uid}')
db.set({avatar: remoteUri}, {merge: true});
}
} catch (error) {
alert("Error: ", error);
}
};
get firestore() {
return firebase.firestore();
}
get uid() {
return (firebase.auth().currentUser || {}).uid;
}
get timestamp() {
return Date.now();
}
}
Fire.shared = new Fire();
export default Fire;
The createUserWithEmailAndPassword() method returns a Promise which resolves with a UserCredential AND (as the the doc indicates) "on successful creation of the user account, this user will also be signed in to your application."
So you can easily get the signed in user by using the user property of the UserCredential, and call the sendEmailVerification() method, as follows:
try {
const userCredential = await firebase.auth().createUserWithEmailAndPassword(user.email, user.password);
await userCredential.user.sendEmailVerification();
//In the next line, you should most probably use userCredential.user.uid as the ID of the Firestore document (instead of this.uid)
cont db = this.firestore.collection("users").doc(this.uid);
//...
} catch (...)
Note that you may pass an ActionCodeSettings object to the sendEmailVerification() method, see the doc.

Not able to get values from the api to chart.js, react js

so this is my api, which is stored in a url
"https://covid19.mathdro.id/api/confirmed"
this is my api index file
import axios from "axios";
const url = "https://covid19.mathdro.id/api/confirmed";
export const fetchData = async () => {
try {
const {
data: countryRegion ,
} = await axios.get(url);
return { countryRegion };
} catch (error) {
return error;
}
};
in this sandbox code, i have tried to take the value of countryRegion from the api, but it appears as undefied in the console.
https://codesandbox.io/s/react-chartjs-2-nqo9n
Looks like you are destructuring incorrectly.
const { data: { countryRegion } } = await axios.get(changeableUrl);
Do this in your api
const { data: countryRegion } = await axios.get(changeableUrl);
Update based on the comment:
If only country is needed in the array, just map thru it and extract countryRegion
export const fetchData = async country => {
try {
let { data: countryRegion } = await axios.get(url);
return { countryRegion: countryRegion.map(country => country.countryRegion) };
} catch (error) {
return error;
}
};

Resources