how can i do Multiple Request using Promise.all using this parameters? - javascript

today I had some problems with my code.. the thing is I have to create a multiple POST request to the API to pass users to a group, so.. the API request is:
POST /users/user-group-membership
{
"userId": "string",
"groupId": 0,
"isActive": true,
}
Basically i have to grab from the users table the userId from each user and for each userId create a multiple request... so what i did was:
const moveTogroup = async (
token: string,
userId: string,
groupId: number,
): Promise<any> => {
const res = await axios({
method: 'POST',
url: `${API}/users/user-group-membership`,
data: { userId: userId, groupId: groupId },
headers: {
Authorization: `Bearer ${token}`,
},
});
const { data } = res;
return data;
};
export const moveAllGroup = (
token: string,
): ThunkAction<void, State, null, UsersActions> => {
return async (dispatch, getState) => {
const { userId, groupId } = getState().FleetUsers;
const convert = userId.toString();
console.log(convert);
dispatch(moveUserToGroupRequest());
try {
const userPromises = userId.map(() =>
moveTogroup(token, convert, groupId),
);
const move = await Promise.all(userPromises);
console.log('moving:', move);
dispatch(moveUserToGroupSuccess(move));
Swal.fire('Saved', 'Your Changes has been saved', 'success');
} catch (error) {
dispatch(moveUserToGroupFailure(error));
Swal.fire('Error', error, 'error');
}
};
};
But as you see this only works for one userId, I grabbing from the state the userId and the groupId, converting the userId to string, and voila is working perfectly, only what I want is depending how much userId I have in the state replied to the request for creating multiple requests and when the user selects in table 2 or 3 users, he or she can move them easily.

If your userId var contains all userIds, you must map it to recover specific information about each userId :
userId.map((elt) => {
const convert = elt.toString();
moveTogroup(token, convert, groupId),
});

Related

Dynamic router and page with Next.js and Prisma

I have cards with product information in my database, I display them successfully on the user's page. Now I want to add a more details button on each card to go to a new page from it (/pages/card/[id]). But I don't really understand how I can pull out the card value by clicking through my API.
const res = await fetch('/api/cards/' + id, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ id: id })
})
if (res.ok) {
const result = await (await res).json()
if (result.redirectUrl) {
router.push(result.redirectUrl as string)
}
}
}
API
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const { id } = req.query
if (req.method === 'GET') {
if (typeof id === 'string') {
const moreDetail= await db.sales.findUnique({
where: {
id: id },
})
res.send({ redirectUrl: '/card'+[id] })
}
}
My card in schema
id String #id #default(cuid())
title String
description String
active Boolean #default(true)
My suggestion would be to introduce another API endpoint that returns an array of all of the available cards, or at least an array of all of the available card ids. After that, create a new page matching your URL format /pages/card/[id].tsx and inside that file, create your page like normal, but also export 2 functions:
getStaticPaths
getStaticProps
These let Next know what paths are available and how to load data for them during the build process.
export async function getStaticPaths() {
const cardIds = await fetch('/api/cards', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
return {
paths: cardIds.map((id) => (
{
params: { id }
},
)),
fallback: false, // setting to false will throw a 404 if none match
};
}
This lets Next know all of the available dynamic routes to generate pages for.
export async function getStaticProps({ params: { id } }) {
const card = await fetch(`/api/cards/${id}`, {
method: 'GET',
headers: {
'Content-Type': 'application/json'
},
});
return {
props: {
card,
},
}
}
This actually loads the data from your API given a card id and passes it into your component to display more details for.
Hopefully that gives you a good jumping off point.

Dynamically Update Existing Data with Prisma

I encountered a problem using next.js in the api routes. Here is the code in question:
////////
schema
////////
model Movie {
id Int #id #unique #default(autoincrement())
title String
year Int
}
///////
fetch request
///////
async function handleSubmit(e) {
e.preventDefault();
onSubmit({
id: Math.floor(Math.random() * 10000),
title: formData.title,
year: formData.year
});
const response = await fetch('/api/movie/[id]', {
method: 'PUT',
body: JSON.stringify(formData)
})
return await response.json()
}
//////
[id].js
//////
export default async({query: { id }, movies}, req, res) => {
const data = JSON.parse(req.body)
const updateMovie = await prisma.movie.update({
where: {
id: parseInt(id)
},
data
})
res.json(updateMovie)
}
export async function getServerSideProps() {
const movies = await prisma.movie.findMany()
return {
props: {
data: movies
}
}
}
Obviously, this code will update the data with an ID of “1”. But what if I wanted to update data with the ID of “4”? How would I do this without having to manually go in the code and change the ID every time?
I have tried putting this variable where the ID is:
const movieId = movies.map((movie) => movie.id === id)
but I get this error every time:
'SyntaxError: Unexpected token u in JSON at position 0'
I don't know what else to do? Any help would be appreciated!

How to delete object from firebase database

I'm trying to figure out how to delete information submitted to the firebase database.
I am trying to delete information under the requests. Example
Here are my actions used to fetch the data:
export default {
async contactArtist(context, payload) {
const newRequest = {
userEmail: payload.email,
message: payload.message
};
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'POST',
body: JSON.stringify(newRequest)
});
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to send request.');
throw error;
}
newRequest.id = responseData.name;
newRequest.artistId = payload.artistId;
context.commit('addRequest', newRequest);
},
async fetchRequests(context) {
const artistId = context.rootGetters.userId;
const token = context.rootGetters.token;
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${artistId}.json?auth=` + token);
const responseData = await response.json();
if (!response.ok) {
const error = new Error(responseData.message || 'Failed to fetch requests.');
throw error;
}
const requests = [];
for (const key in responseData) {
const request = {
id: key,
artistId: artistId,
userEmail: responseData[key].userEmail,
message: responseData[key].message
};
requests.push(request);
}
context.commit('setRequests', requests);
},
};
I'm trying to set up a button that will delete the selected request object.
Your code is sending a POST request, which tells Firebase to generate a unique key. From the documentation on saving data:
POST: Add to a list of data in our Firebase database. Every time we send a POST request, the Firebase client generates a unique key, like fireblog/users/<unique-id>/<data>
The delete a node, send the DELETE verb/method to that path:
const response = await fetch(`https://find-artist-d3495-default-rtdb.firebaseio.com/requests/${payload.artistId}.json`, {
method: 'DELETE'
});

Trying to dynamically set .find() parameters from client input - mongodb:Atlas

I am trying to use data from the client, which they would type into an input box. The idea is to use this for finding in my database to pull the data with the same username. on my Mongo DB:Atlas collection.
So its to use it like this to get the names from the database, .find({"username": request.body})
However, I keep getting the error "CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1" on my terminal.
But when I try to hard code it onto the .find({"username": "name"), it works fine. Does anyone have any ideas?
**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
Actually, you're passing the object {username : "value"} to the find method. You need to pass the string.
app.post('/database', (request,response) => {
const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

How to optimize an API fetch to be less redundant

I'm building a React App which consumes an API and what I build for now is 2 functions which both GET the same URL but changing the second part of the API Endpoint like URL/?search or URL/?i=123 but what I would like to achieve is to have less redundant code so I was wondering to make one function which just takes the same URL and change the second part of the URL based on the call.
By the way, this approach gives me problems.
The code I did originally was this:
import {API_MOVIE_URL, API_KEY} from "./ApisConst";
export const getMoviesBySearch = async search => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
export const getMoviesInfo = async movieID => {
try {
const url = `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`;
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
And the change I tried is:
const fetchAPI = async ({type, query}) => {
const queryParams = {
byString: `&${query}`,
byMovieId: `&i=${query}&plot`,
};
const endpoint = `${API_MOVIE_URL}?apikey=${API_KEY}${queryParams[type]}`;
console.log("fetching", endpoint);
return fetch(endpoint)
.then(res => res)
.catch(() => ({
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
}));
};
export const getMoviesBySearch = async search =>
await fetchAPI({type: "byString", query: search});
export const getMoviesInfo = async movieID =>
await fetchAPI({type: "byMovieId", query: movieID});
But this second approach gives me an error in the console which is:
Response {type: "cors", url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie", redirected: true, status: 200, ok: true, …}
body: (...)
bodyUsed: false
headers: Headers {}
ok: true
redirected: true
status: 200
statusText: ""
type: "cors"
url: "https://www.omdbapi.com/?apikey=API_KEY&s=harry+potter&type=movie"
The first approach works perfectly but the second one none and trying to get a solution but cannot really think what to do to get this code better optimized.
Since the queries are identical except for the url, create a query generator (createMoviesQuery) that accepts a function that generates the url (urlGenerator), and returns a query function
Example (not tested):
import {API_MOVIE_URL, API_KEY} from "./ApisConst";
const createMoviesQuery = urlGenerator => async (...params) => {
try {
const url = urlGenerator(...params);
const response = await fetch(url);
const json = await response.json();
return json;
} catch {
return {
success: false,
result: [],
message: "There is an issue to get data from server. Please try again later.",
};
}
};
export const getMoviesBySearch = createMoviesQuery((search) => `${API_MOVIE_URL}?apikey=${API_KEY}&${search}`);
export const getMoviesInfo = createMoviesQuery((movieID) => `${API_MOVIE_URL}?apikey=${API_KEY}&i=${movieID}&plot`);

Categories

Resources