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.
Related
I'm using PayPal in sandbox mode and #paypal/react-paypal-js in my React application and I'm using .NET 5 as my REST API.
Here is my payload when I want to create an order:
{
"totalAmount": 102,
"tax": 0,
"fee": 2,
"paymentMethod": 1,
"items": [
{
"amount": 100,
"reciver": "vala",
"phone": "0912351231",
"email": "vala#gmail.com",
"sender": "ali",
"count": 1
}
]
}
And here is part of my react code that call PayPal API:
<BoxPayment isRtl={isRtl}>
<Text as="h3">{translations.buyPage.paymentMethodTitle}</Text>
<Text as="p">{translations.buyPage.paymentMethodSubTitle}</Text>
<div style={{ 'paddingTop': '.5rem' }}>
<PayPalScriptProvider options={initialOptions}>
<PayPalButtons createOrder={(data, actions) => createOrder(data, actions)}
onApprove={(data, actions: any) => {
console.log('data', data);
console.log('actions', actions);
return actions.order.capture().then((details: any) => {
console.log('details', details);
const name = details.payer.name.given_name;
});
}} />
</PayPalScriptProvider>
</div>
</BoxPayment>
But after successful payment here's what I receive when I console.log data object:
{
"orderID": "48G91901G2470590C",
"payerID": "NBPJH63GK5H5Q",
"paymentID": null,
"billingToken": null,
"facilitatorAccessToken": "A11VAJ-tUcUqKkJgAhnyfVGVYg6Z57SvqHfspQqB8vtUDjDzBMIBlvO6rDvwdIjW7aJwvQQYeMAGyWitChtVZ8LyBzCw"
}
What I am missing?
Within onApprove, the order hasn't been captured when you are printing that data. Capture the order first. When an order is captured, its transaction ID will be in the response's purchase_units[0].payments.captures[0]
If you need to do anything important with that ID, such as store it in a database, used a server-side integration (not actions.order.capture nor actions.order.create, client-side code is not for database operations). See the optional step #5 in the 'Add and modify the code' section of the guide for Integrate Checkout, and be sure to use the client-side error handling code in its linked demo pattern example.
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
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
Edit to the makers of AoR : Your framework suffers from horrid documentation. You should really focus on that, people would really adopt it then.
I cant for the life of me decipher how admin-on-rest does the 'rest' part. If there is a better framework with better documentation, Im open to that.
Im very new to react, so thats probably part of it.
What I can discern is that
1) The [Admin] tag takes a prop 'restClient', and this is a function that sets your base path to your JSON source, then returns a function with a specific signature (takes 3 arguments, returns a promise).
2) Then a [Resource] tag adds to the path with name="posts" and makes a list, which (heres where it turns to magic) basically does a wget to your database then iterates over the results.
What I want to do : hook up couchDB to admin-on-rest. I already have a few test docs made on localhost. The couchDB url looks like :
http://127.0.0.1:5984/myproject/_design/getclients/_view/getclient/
and this works in postman, giving me a json object like this :
{
"total_rows": 4,
"offset": 0,
"rows": [
{
"id": "afc3bb9218d1a5c1e81ab3cc9f004467",
"key": {
"status": "active",
"rating": 9.1,
"bio": {
"fname": "Sam",
"mname": "TestMName",
"lname": "TestLName",
"address": "712347 B Street",
"state": "CA",
"city": "Los Santos",
"zip": "90211",
"phone": "123-456-7890",
"email": "sam#samsemail.com",
"username": "TestSam",
"password": "abc123"
}
},
"value": null
},
At this point Im so confused I dont know where to look.
Heres my code now :
//App.js
import React from 'react';
import { jsonServerRestClient, Admin, Resource } from 'admin-on-rest';
import { PostList } from './Posts.js';
const App = () => (
<Admin restClient={jsonServerRestClient('http://127.0.0.1:5984/myproject/')}>
<Resource name="_design/getclients/_view/getclient" list={PostList} />
</Admin>
);
export default App;
And
//Posts.js
export const PostList = (props) => (
<List {...props}>
<Datagrid>
<TextField source="status" />
<TextField source="rating" />
</Datagrid>
</List>
);
The page loads but a little pink box pops up at the bottom saying :
The X-Total-Count header is missing in the HTTP Response. The jsonServer REST client expects responses
The RestClient is a bit of a murky beast. Not perfectly documented for sure.
But it is in the end quite straightforward if you know how the whole thing works together.
1) Admin-On-Rest has defined some REST types (below). These are usually shot off by Redux actions (in their meta tag). The system scans for these rest types and if it sees them, then it calls the RestClient
GET_LIST
GET_ONE
CREATE
UPDATE
DELETE
GET_MANY
GET_MANY_REFERENCE
The REST client is called with these types and some other params. It is the job of the rest client to interpret the type and then use the params to make a request to your API. For this AOR uses the new Fetch API that is built into browsers.
You can access it by calling. You should also go into AOR source code and check out how it works.
import { fetchUtils } from 'admin-on-rest';
2) The X total count is a header field that AOR needs for all responses to the GET_LIST type.
You can set this quite simply in your API. I use loopback and I set the X-Total-Count manually in a remote hook (don't worry about it if you don't know it)
It seems your api is still using the JSON server. JSON server is a dummy API. So your app is not connected to your couchDB right now.
https://github.com/typicode/json-server
If you are not using an api server like express or loopback, then you can also configure your restClient do all request and response handling. You have to construct the URL. Read the below link so you can follow my example code further down.
https://marmelab.com/admin-on-rest/RestClients.html#decorating-your-rest-client-example-of-file-upload
so something like this.
if (type === 'GET_LIST' && resource === 'posts') {
const url = http://127.0.0.1:5984/myproject/_design/getclients/_view/getclient/
options.method = 'GET';
return fetchUtils.fetchJson(url, options)
.then((response) => {
const {headers, json} = response;
//admin on rest needs the {data} key
return {data: json,
total: parseInt(headers.get('x-total-count').split('/').pop(), 10)}
})
You can also write a function like this to handle the request and response.
function handleRequestAndResponse(url, options={}) {
return fetchUtils.fetchJson(url, options)
.then((response) => {
const {headers, json} = response;
//admin on rest needs the {data} key
const data = {data: json}
if (headers.get('x-total-count')) {
data.total = parseInt(headers.get('x-total-count').split('/').pop(), 10)
} else {
data.total = json.length // this is why the X-Total-Count is needed by Aor
}
}
}
// handle get_list responses
return {data: json,
total: } else {
return data
}
})
}
The above code has been formatted in the window and so might not work straight out of the box. But I hope you get the idea.
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;
}