Github user finder api, how to return multiple users per search? JS - javascript

Hello I am using github api to create github user finder. my question is how to manipulate on api link to get users which include e.target.value of the searchbar and not only that one that exactly matches.
here is my code
const [finalData, setFinalData] = useState([]);
const handleSearch = async (e) => {
try {
const URL = `https://api.github.com/users/${e.target.value}?
client_id=e25d1dbedde5215999ef&client_secret=ee080580b7c4f19688ccaef6844c3fe88bb811d`;
Promise.all([fetch(URL).then((res) => res.json())]).then((data) => {
if (data) {
setData(data);
}
});
} catch (err) {
console.log(err);
}
};
const setData = (data) => {
data && setFinalData(data);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

You can use the Search users endpoint. There is a query parameter (q) that allows you to use multiple search criteria documented here
Here's an example using Octokit, but if you still want to use fetch, the endpoint should be https://api.github.com/search/users
Note: I really hope the client secret you are exposing here is for a test application.
Search GitHub users                                                                                
View in Fusebit
const userSearch = ''; // Specify the search text here
const usersResponse = await octokit.rest.search.users({
q: userSearch,
per_page:100
});
const { total_count, items } = usersResponse.data;
console.log(`Listing ${items.length} users of ${total_count} \n`, items.map(user => user.login));

Related

Value (number) is different from the MongoDB to the react client async call

Problem:
An entire field of my MongoDB's collections' is not transmitted correctly from the db to the react client. For an exemple, the first element of this field is tweet_id: 1537466989966413825 in my DB. It becomes tweet_id: 1537466989966413800 when I fetch from my client.
My steps
I pull my data from the MongoDB using their App services' function like that:
exports = function(){
var collection = context.services.get("mongodb-atlas").db("meme_news").collection("news");
return collection.find({});
};
When I press the Run button of their built-in terminal, the correct data is displayed.
On my react's application, I perform the fetch like that:
useEffect(() => {
getData();
}, []);
const getData = async () => {
let getAllData = await user.functions.getAllData();
// all these data are wrong
let tweetId = getAllData
.map((ele) => {
return ele.tweet_id;
})
let tweetIdFirstEle = tweetId[0];
// this return 1537466989966413800
// It should return 1537466989966413825
};
Why is my async/await altering my Mongodb data? I have no idea what is going on here.

How best to add pagination to a search result query in Reactjs?

I have a MERN stack application and I have written the search query and pagination in Nodejs, I implemented the pagination part in Reactjs and wanted to implement the search query too. It is working but without pagination. I was like what if the search result is over 20 results and I simply want to make it two pages. I could do something like 12 search results per page. Is there a way to do this? Can I add both search and pagination queries in a single URL? Here is my nodejs code:
const DEFAULT_PAGE_NUMBER = 1
const DEFAULT_PAGE_LIMIT = 12;
const getPagination =(query) =>{
const page = Math.abs(query.page) || DEFAULT_PAGE_NUMBER;
const limit = Math.abs(query.limit) || DEFAULT_PAGE_LIMIT;
const skip = (page -1) * limit
return {
skip,
limit
};
};
const getAllPosts = async (req, res) =>{
const {skip, limit} = getPagination(req.query);
const {searches} = req.query;
if(searches){
posts = await Post.find({title: {$regex: searches.toString(), "$options": "i"}}).populate('username', 'username').sort({createdAt:-1})
.skip(skip)
.limit(limit)
}
}
Now, in Reactjs, I did something like this for pagination query:
useEffect(()=>{
try{
const response = await axios.get(`/posts/?page=${path}`);
}catch(err){
}
}, [path]);
This works for pagination and posts are displayed 12 per page.
Now, in Reactjs, I did something like this for search query:
useEffect(()=>{
try{
const response = await axios.get(`/posts/?searches=${path}`);
}catch(err){
}
}, [path])
Now, this works. It fetch posts based on the search term the user input. The problem is that the result could be way more than I wanted in a page. Is there a way I could integrate the pagination query that I wrote also into this so that when a search result is more than 12, the other posts would be called on the next page?
datatables plugin provides really good pagination out of the box
I sorted this out by passing the search parameter in the body and the pagination on the query. This sorted out my issue. See sample codes
const { skip, limit } = getPagination(req.query); // pagination
const search = req.body.search; // search
if (search) {
posts = await Post.find({ title: { $regex: search.toString(), "$options": "i" } })
.populate('username', 'username').sort({ createdAt: -1 })
.skip(skip)
.limit(limit)
} else {
/* fetch the entire posts if there is no search parameter. */
}

How to fetch all the documents with unique id from firestore database using React?

[Firestore SS][1]
[1]: https://i.stack.imgur.com/EI1Dm.png
I want to fetch each document as displayed in SS it's stored as Pets + unique_userId.
I am unable to fetch all data together. Just able to fetch one data of a particular user using the code below.
const [info,setInfo]=useState([]);
useEffect(() => {
db.collection("pets ESYXOPqlJpZ48np8LfNivnh9pvc2").onSnapshot((snapshot) =>
setInfo(snapshot.docs.map((doc) => doc.data()))
);
},[]);
Here ESYXOPqlJpZ48np8LfNivnh9pvc2 this is the userID of each unique user
Please help me out to fetch all the Pets data instead of hardcoding and fetching one particular data.
Try the following code,
const [docs, setDocs] = useState([]);
useEffect(() => {
const querySnapshot = await getDocs(collection(db,"pets ESYXOPqlJpZ48np8LfNivnh9pvc2"));
const document =[];
querySnapshot.forEach((doc) => {
document.push({
...doc.data(),
id: doc.id
});
});
setdocs(document);
}, []);
I'm guessing the appended id is a reference to the owner's id? In this case, would it be an option to fetch the owner list and use everyone's id to build a list of collection ids and then get all of their data?
If not, I only see to options:
Rethink your database structure - maybe use a unified pets collection and have a reference with/to that id in the pet documents.
Create a cloud function in which use #google-cloud/firestore to get the list of collections. There are tons of resources out there to help you get started with firebase cloud functions. Their documentation is pretty good also, and probably the most up-to-date
const functions = require('firebase-functions')
const { Firestore } = require('#google-cloud/firestore');
module.exports = functions
.region('europe-west3') // use the region you want here
.https.onRequest(async (request, response) => {
try {
const firestore = new Firestore();
const collections = (await firestore.listCollections()).map(collection => collection.id)
response.json({ data: collections })
} catch (error) {
response.status(500).send(error.message)
}
})
You'll get and endpoint which you can use to fetch the collection ids (e.g.: https://your-project-name.cloudfunctions.net/collections)
const [pets, setPets] = useState([]);
const [collectionIds, setCollectionIds] = useState([])
useEffect(() => {
fetch('https://your-project-name.cloudfunctions.net/collections')
.then(response => response.json())
.then(({ data }) => setCollectionIds(data))
}, [])
useEffect(() => {
collectionIds.forEach((collectionId) => {
// There are better ways to do this,
// I'm just using your approach so you can focus on the rest of the code
db.collection(collectionId).onSnapshot((snapshot) => {
setPets((currentPets) => [...currentPets, ...snapshot.docs.map((doc) => doc.data())])
})
})
}, [collectionIds])
Please note that these are very high-level implementations, there's no error handling, no teardowns or anything, so keep that in mind. Hope it helps, good luck!

Next JS and Vercel - development vs production

I’ve built a basic movie DB app in Next JS to see how the framework works. It’s an app that allows you to perform CRUD operations to firebase, utilising the NextJS API endpoints.
I have the app working fine in development, however it does not work at all once to Vercel. I was wondering if anyone can shed some light?
Here is the first 'get all data' call upon initialisation. The other API calls follow the same pattern. None work once deployed.
My index page has this getInitialProps function…
Home.getInitialProps = async () => {
const categories = await getCategories()
const movies = await getMovies()
const images = movies.map(movie => {
return {
id: `image-${movie.id}`,
url: movie.cover,
name: movie.name
}
})
return {
movies,
images,
categories
}
}
This fires off the getMovies function here…
export const getMovies = async () => {
const res = await axios.get('http://localhost:3000/api/movies')
return res.data
And the API endpoint it hits looks like this…
import firebase from '../../lib/firebase';
export default async(req, res) => {
const moviesRef = firebase
.collection('movies');
const snapshot = await moviesRef.get();
const movies = [];
snapshot.forEach(doc => {
movies.push({ id: doc.id, ...doc.data() })
})
res.json(movies)
Thanks in advance!
you should use your server link, not localhost.
You shouldn't hardcode http://localhost:3000 in the request's URL. You should omit it altogether since you're using Next.js API routes (same-origin).
export const getMovies = async () => {
const res = await axios.get('/api/movies')
return res.data
}
Edit: The above solution would work with API routes if the request was happening on the client-side only.
Since the request is made in getInitialProps, you should simply move the logic in your API route to a separate function (could very well be getMovies in this case) and call that directly in getInitialProps instead.
export const getMovies = async () => {
const moviesRef = firebase.collection('movies');
const snapshot = await moviesRef.get();
const movies = [];
snapshot.forEach(doc => {
movies.push({ id: doc.id, ...doc.data() })
});
return movies;
}

How to read list of data from Firebase?

I'm building simple app using Firebase just to get a sense how to work with it.
Currently, I create notes using following approach
const notes = db.ref(`users/${user.uid}/notes`).push();
notes.set({
title,
description
});
But, how do I retrieve this list of data ?
Thanks in advance.
Here's my approach based on the documentation:
const readUsersFromSnapshot = snapshot => {
const users = [];
snapshot.forEach(child => {
users.push(child.val());
});
database.ref('users').off();
return Promise.resolve(users);
};
const getUsers = () =>
database
.ref('users')
.once('value')
.then(readUsersFromSnapshot);
// getUsers().then(users => {
// users array
// });

Categories