Make Axios Limit the Number of Responses - reactjs

I am attempting to make an axios GET call to an API to retrieve some JSON data. The data is stored in an array with multiple objects each containing the same keys. There are hundreds of objects in this array but I only want to return the first ten. I am aware I can truncate the data set once it is returned but I am wondering if there is a way to limit the amount of responses to my API call.
Here is an example of the data set:
[
{
"userId": 1,
"id": 1,
"title": "The Great Gatsby",
"author": "F. Scott Fitzgerald"
},
{
"userId": 1,
"id": 2,
"title": "1984",
"author": "George Orwell"
},
{
"userId": 1,
"id": 3,
"title": "The Count of Monte Cristo",
"author": "Alexandre Dumas"
},
]
and my axios request is simple as well:
router.get('/', (req, res) => {
axios.get(`https://jsonwebsit.info.com/posts`)
.then( response => {
res.send(response.data)
})
.catch(err => {
console.log('Error getting all data from API', err)
})
});

Actually, you can limit the number of responses from a certain API endpoint.
Just add params as an object as a second parameter while making the request.
For example:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/todos',{
params: {
_limit: 10
}
})
.then((res) => {
this.setState({
todos: res.data
});
})
}
Here you are limiting the response to 10 from jsonplaceholder API.
You could also call https://jsonplaceholder.typicode.com/todos/?_limit=10 and would get the same result.
Hope it helps.

On your side there's nothing you can do until pagination is implemented on API side. Depending on the way it's implemented, you will probably make requests to API sending params like offset, page, limit- these are the most common params' names saying how many elements should API return. But if that's 3rd party provider and their docs are not saying anything about such possibility, you're most likely won't be able to do what you want

Related

How to mutate specific object in an array using SWR

I have the following array
[
{
"idChatPublic": 17,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "hello",
"avatar": null,
"createdAt": "12:43",
"chatLike": []
},
{
"idChatPublic": 33,
"idChatRoom": 2,
"idSender": "6c25110d-4256-42e1-8205-b75ece274487",
"username": "Hudson Thadeu Teixeira",
"message": "jam",
"avatar": null,
"createdAt": "13:07",
"chatLike": [
{
"idChatLike": 1,
"idChatPublic": 33,
"idUser": "",
"createdAt": "2022-02-14T08:59:34.000Z"
}
]
}
]
How can mutate an specific object of this array and add an object
to the "chatLike" array using SWR?
I have the following function:
async function sendLike() {
const newLike = {
idUser: myUser.userId,
}
mutate(
async (data) => {
console.log(data[messageIndex]) // This log returns specific object in the array
// Handle mutation
},
false
)
socket.emit('send_like', newLike)
}
Please guys I've been trying this for a while would be great If someone gives me a hand :D
You're using SWR with a websocket, which is an anti-pattern. SWR is meant for managing data that's fetched via REST or GraphQL requests, and it can be configured to refetch data on a regular interval. It's not a real time connection. Websocket on the other hand is real time. Consider if SWR is really best for your project - you probably don't need it.
Anyway, I also noticed some issues with how your mutate() is written so here's some feedback.
you must pass an ID into first argument
if you pass a function into mutate's second argument, it must return the new data
an easy way to update a specific item in an array is by using .map() and spread ... syntax
function sendLike() {
const newLike = {
idUser: myUser.userId,
}
// send request to update the source
// this is usually an REST request such as 'POST, UPDATE' etc
socket.emit('send_like', newLike)
// mutate local data
mutate(
'/api/chat', // ID must match ID used in the useSWR hook,
data => data.map(chat => chat.idChatPublic === idChat : {
...chat,
chatLike: [
...chat.chatLike
newLike
]
} : chat),
false
);
}

React API call, render data with QuickBase's new RESTful API

I'm trying to figure out what i'm doing wrong here... I've been out of coding for awhile and trying to jump back in for an external application utilizing QuickBase's RESTful API. I'm simply trying to get data from QuickBase to be used outside in an external app to create charts/graphs.
I'm not able to use GET as it gives me only the field names and no data, if I use POST, then I get the values of these fields as well. I'm able to get all the data rendered in the console, but am struggling to get each field rendered to be used in the app.
let headers = {
'QB-Realm-Hostname': 'XXXXXXXXXXXXX.quickbase.com',
'User-Agent': 'FileService_Integration_V2.1',
'Authorization': 'QB-USER-TOKEN XXXXXX_XXXXX_XXXXXXXXXXXXXXXX',
'Content-Type': 'application/json'
}
let body = {"from":"bpz99ram7","select":[3,6,80,81,82,83,86,84,88,89,90,91,92,93,94,95,96,97,98,99,101,103,104,105,106,107,109,111,113,115,120,123,224,225,226,227,228,229,230,231,477,479,480,481],"sortBy":[{"fieldId":6,"order":"ASC"}],"groupBy":[{"fieldId":40,"grouping":"equal-values"}],"options":{"skip":0,"top":0,"compareWithAppLocalTime":false}}
fetch('https://api.quickbase.com/v1/records/query',
{
method: 'POST',
headers: headers,
body: JSON.stringify(body)
})
.then(res => {
if (res.ok) {
return res.json().then(res => console.log(res));
}
return res.json().then(resBody => Promise.reject({status: res.status, ...resBody}));
})
.catch(err => console.log(err))
Hoping to get some help getting the data rendered to be used in React, as well as any tips from anyone who's used QuickBase's new API calls in their realm! And I apologize if it's an easy question/issue, haven't been in React for a couple years... and I'm feeling it!
Thanks!
A successful response from Quickbase for this call has a property data which is an array of the records returned. Each element of this array is an object where the FID for each field returned is a key for nested object - or objects for some field types - with the field's value. Here's a very contrived example:
{
"data": [
{
"1": {
"value": "2020-10-24T23:22:39Z"
},
"2": {
"value": "2020-10-24T23:22:39Z"
},
"3": {
"value": 2643415
}
}
],
"fields": [
{
"id": 1,
"label": "Date Created",
"type": "timestamp"
},
{
"id": 2,
"label": "Date Modified",
"type": "timestamp"
},
{
"id": 3,
"label": "Record ID#",
"type": "recordid"
}
]
}
If you put the data array of the response directly into state with const [quickbaseData, setQuickbaseData] = useState(res.data); for example, you need to keep the structure of the response in mind when accessing that data. If I want to get the value of FID 3 from the first record in the response I would need to use quickbaseData[0]["3"].value. For most field types value will be a string or integer but for some field types it will be an object. You can see the way values are returned for each field type in Field type details.
Depending on your needs you might consider processing the Quickbase response into a new, simpler array/object to use in your application. This is especially helpful if the value being returned needs additional processing such as converting into a Date() object. This would also allow you to make your application API agnostic since other than initially processing the response from Quickbase the rest of your application doesn't have to have any knowledge of how Quickbase returns queried data.
On the Quickbase side of things, there isn't the equivalent of 'SELECT *' so to get data for all fields of a table where you don't know the schema (or it changes frequently) you can run a GET on the Fields endpoint: https://developer.quickbase.com/operation/getFields an then use the field IDs in the response to make the POST call to /records/query

Postman response in different order to console log response from request

When using Postman to test an API a request, the response i get is unordered, which is what I want, i.e.:
}
"23": "Kevin",
"2": "James",
"12": "Michael"
}
However, when I log the response, it automatically sorts it to:
}
"2": "James",
"12": "Michael",
"23": "Kevin"
}
I am getting the response in a promise:
return this.client.post('/url', data)
.then(response => {
console.log('api response: ', response);
Is there anyway I can prevent the ordering of the response so I can render the data as desired? I am not sure where, or why the order of the data is different.
Any help will be massively appreciated!
You cannot and should not rely on the ordering of elements within a JSON object.
From the JSON specification at http://www.json.org/
An object is an unordered set of name/value pairs
As a consequence, JSON libraries are free to rearrange the order of the elements as they see fit. This is not a bug.

Splitting the string url in reactjs

I am trying to call the backend api which results in the details of the specific product based on id for example the api is http://localhost:54729/api/product/1 the 1 in the api is the id of the specific product. I am using redux and axios to get the data from the api.
EDIT:
The response from the api from which I am getting is the following
[
{
"id": 0,
"title": "TestProductAzure",
"description": "<p>While working with the EF Core Code-First approach, we create the classes for our domain entities first. Later, we’ll create the database from our code by using migrations. This is the opposite of the Database-First approach where we design our database first and then create the classes which match our database design.In the EF Core Code-First approach, we have full control over the code and the database is just a store without any logic. This approach is helpful in situations where we are starting with the development of a new project and we don’t have a clear picture of how our database should look like yet.We don’t have to worry about creating and updating the database. We can just make the changes in our code and then sync everything easily with the database. The important thing to note is that the manual changes that we make to the database could be lost during migration. So we should make changes to the code only.</p>",
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/1",
"type": "Internal",
"rank": 5
},
{
"id": 0,
"title": "Support | example.com",
"description": null,
"owner": null,
"link": "/search/product?url=https://www.example.com/support/",
"url": "https://www.exampl.com/support/",
"type": "External",
"rank": 3
},
{
"id": 0,
"title": "TestProductForAzure",
"description": null,
"owner": "Seeded Company",
"link": null,
"url": "http://localhost:54729/api/product/3",
"type": "Internal",
"rank": 0
},
The above response is the response when someone search something with the keyword. Now what I want if the user clicks on the url that has the api like http://localhost:54729/api/product/ I want to check the last number of the api i.e. the id and get the response from that forexample, if the user clicks on http://localhost:54729/api/product/2 . I want to pass the id 2 to the function which will then get pass from action and axios.get give the response.
My Action look like this
export function detailsProduct(id) {
const token = userService.getToken();
console.log(token);
const api = `/product/${id}`;
axios
.get(apiBaseUrl + api, { headers: { Authorization: `Bearer ${token}` } })
.then(res => {
console.log("helloProductDetails", apiBaseUrl + api);
try {
store.dispatch({
type: PRODUCT_DETAILS,
payload: res
});
} catch (err) {
console.log("error", err);
}
});
My Reducer look like this:
case PRODUCT_DETAILS:
console.log(
"action",
action,
"actionPayload",
action.payload,
"state",
state
);
return {
...state,
products: action.payload,
loading: false,
totalRecords: action.payload.length
};
and my .jsx react look like this
function onClickHandler() {
console.log("calling Details Product, HardCodedly");
detailsProduct(1);
}
return (
<div className="row">
<div className="s130">
{/* <div class="col-lg-8 col-xs-8 col-sm-12 col-md-7"> */}
<div className="col-lg">
<div className="container">
{result.type === "Internal" ? (
<Link to={DoctorProductLocation.path} onClick={onClickHandler}>
<h3>{result.title}</h3>
</Link>
) : (
//Try With OnClick Function
<a href={result.url} target="_blank">
<h3>{result.title}</h3>
</a>
)});
As you did notice , I'm sending the id hardcoded for now just to check if I am getting the information, which is working fine. But All I want to do is that when I click on the response it will automatically check the id and send us the response of that.
I thought of splitting the url until the id and pass it to the function action. But I don't know How? Or else if you have any other good idea, I will be thankful to you.

Best practice Backand regarding JSON transformation and related objects

I am currently trying to figure out how to setup my Backand app and its REST API. This question is related to question: Backand deep querying. However, I was hoping that I could get some best practice code examples on how to perform server side code to perform a loop and create a JSON responds with the following criteria:
I want to be able to make a REST request to Backand and get one data object back that has manipulated/merged two data objects from my database.
I have an object called "media" and another named "users". Obviously, users contain user information and media contains information on a picture that the user has uploaded. The two objects are related by the userId and by collection set in Backand. I want to make a GET request that responds with a JSON object with all pictures and a nested user object on each picture object that contains the related user information. I know that I get back "relatedObjects", and I could then make some manipulation on the client side, but I am hoping that there is another easier way to do this from the Backand administration system either on server side code or as a query.
So, my question is, what's the best way to produce a REST call that responds a database object with nested related data object through Backand?
Here's the object models (shorten for clarity):
User object model as set up in Backand
{
"name": "users",
"fields": {
"media": {
"collection": "media",
"via": "user"
},
"email": {
"type": "string"
},
"firstName": {
"type": "string"
},
"lastName": {
"type": "string"
}
} }
Media object model as set up in Backand
{
"name": "media",
"fields": {
"description": {
"type": "string"
},
"thumbnail": {
"type": "string"
},
"fullImage": {
"type": "string"
},
"user": {
"object": "users"
}
}}
Final JSON response that I am looking for:
{
description: 'Blah',
thumbnail: 'someImageUrl.jpg',
fullImage: 'someImageUrl.jpg',
user: {
firstName: 'John'
lastName: 'Smith'
email: 'john#smith.com'
}
}
Just in case anybody else comes across this, I chose to do it with server-side javascript code, since my backend, SQL and NoSQL query skills are very weak. I'm guessing a noSQL query would probably be better in terms of performance. And I would still like to see how it could be done in noSQL. Anyway my server-side javascript code in a Backand action does the job. Here it is:
/* globals
$http - Service for AJAX calls
CONSTS - CONSTS.apiUrl for Backands API URL
Config - Global Configuration
socket - Send realtime database communication
files - file handler, performs upload and delete of files
request - the current http request
*/
'use strict';
function backandCallback(userInput, dbRow, parameters, userProfile) {
var response = [];
var request =
$http({
method: "GET",
url: CONSTS.apiUrl + "/1/objects/media",
headers: {"Authorization": userProfile.token},
params: {
exclude: 'metadata',
deep: true
}
});
var object = request.data;
var related = request.relatedObjects.users;
for (media in object) {
if (object.hasOwnProperty(media)) {
for (user in related) {
if (object[media].user == related[user].id) {
response.push({
id: object[media].id,
thumbnailUrl: object[media].thumbnail,
description: object[media].description,
fullName: related[user].firstName + ' ' + related[user].lastName,
email: related[user].email
});
}
}
}
}
return response;
}

Resources