How to parse json in react native - javascript

I'm working on react native project, and i'm calling API and extracting data from it , the data is succesfully extracted but I want to take arguments from the extracted data and I did'nt know how
This is the code for fetching api :
Axios({
url: '/Authentification',
method: 'get',
baseURL: 'http://smart.netrostercloud.com/api',
transformRequest: [
function (data, headers) {
return data;
},
],
transformResponse: [
function (data) {
// console.log(data);
setData3(data);
},
],
headers: {
Authorization: 'Basic UxvwJc1GWjkOCyZoIHGuCD05gDUB72sqrgK30FgILho=',
},
});
console.log(data3);
I've used data3 to extract the data in my main function so it can be visible.
This is the data :
I want to take CompanyCode,UserName,Password,FirstName and LastName

Firstly : axios its n asynchronous function, so its return a promise,
Actually i dont prefere use this patern in simple api call l, but its good way if you know this concept and use oop like create instance of axios to reusable and cancel connectiin when component will unmount.
Fot this i prefere use this way
Const getUserData= async () =>{
try {
Const {data} = await axios.get(baseurl+route, headers , options)
data & & SetData({username:data. User. Username,........... } )
Dosomthing...
}
Catch(error) {
Dosomthing...
}

Before you storing data into data3 you need to stringify the data like this setData3(JSON.stringify(data));
and then try this:
if (data3) {
const COMP_NAME = data?.user?.CompanyCode;
const USER_NAME = data?.user?.UserName;
CONST FIRST_NAME = data?.user?.FirstName;
CONST LAST_NAME = data?.user?.LastName;
}

Related

Extra semicolon showing up in axios get request

I am trying to dynamically build an axios get request, and have currently hardcoded some values in my parameters array to test with like so:
const parameters = [
'table=cumulative',
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
'order=koi_period',
'format=json'
];
let searchParameters = '';
const api = axios.create({
baseURL: 'https://exoplanetarchive.ipac.caltech.edu/cgi-bin/nstedAPI/nph-nstedAPI'
});
for (let element in parameters) {
if (element !== '') {
searchParameters += `?${parameters[element]}`;
}
}
I then add this query to my axios get request below:
export const getExoplanets = async () => {
try {
searchParameters = searchParameters.replace(/;/g, "");
console.log(`${searchParameters}`);
return await api.get(`${searchParameters}`);
// return await api.get(`?table=cumulative&where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2&order=koi_period&format=json`);
} catch (error) {
return error;
}
};
When the variable version runs the api returns the error:
ERROR
Error Type: UserError
Message: Constraint contains an illegal keyword: ";"
However when the commented out, hard coded version runs it works just fine. At some point an extra semicolon is being added to the request. I assume it is being added at the end, but I can't find where or how. Any ideas how to fix this?
Axios supports easy query parameters using the params config option.
Just provide an object of key / value pairs and Axios will do all the encoding for you
const params = {
table: "cumulative",
where: "koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",
order: "koi_period",
format: "json"
}
return api.get("", { params })
// or return api.get("", { params: params })
This will send a request to
?table=cumulative&where=koi_disposition+like+%27CANDIDATE%27+and+koi_period%3E300+and+koi_prad%3C2&order=koi_period&format=json
it seem you having an issue in this bellow line you have used the \ rest of this you can wrap all the things in the double quote.
'where=koi_disposition like \'CANDIDATE\' and koi_period>300 and koi_prad<2',
"where=koi_disposition like 'CANDIDATE' and koi_period>300 and koi_prad<2",

Cannot acces JSON element react js

I have the following code:
const [intrebari, setIntrebari] = useState([])
useEffect(() => {
let idVar = localStorage.getItem('idVarianta');
idVar = JSON.parse(idVar)
axios({
method: "POST",
data: {
idVarianta: idVar,
},
withCredentials: true,
url: "http://localhost:4000/getIntrebari",
}).then((res) => {
console.log(res)
const data = res.data;
setIntrebari(data);
console.log('Data has been recieved');
});
}, [])
which is returning me this:
How can I access the data? If I try intrebari[0].intrebare it gives me "Cannot access property intrebare of type undefined". Any idea? I tried also to console log intrebari[0] and it's displaying the first element, but when i'm trying to access intrebari[0].intrebare it gives me the error described above.
Thanks
Instead of setIntrebari(data), try setIntrebari(res).
Solved it by adding this. The problem was that the component was rendering before the data was fetching.
function getIntrebare() {
if (intrebari.length !== 0) {
return intrebari[questionIndex].intrebare;
}
return "";
}

JavaScript - Url encoding of Array type parameters

I can't figure out how to URL encode array params in an elegant way, in order to send XHR requests from my Vue.js client to my Symfony PHP API.
For example i have this GET method endpoint:
/question/list?subjects={idSubject}
It lists Question entity items and optionally, accepts params in order to filter results by them (subjects in this case)
The desired one would be:
/question/list?subjects[]={idSubject}&subjects[]={idSubject}
I'm using Axios for Vue.js to perform XHR requests and i created a main class that implements the methods that i want.
As the get() method doesn't support 'data' property in config object, i implemented it at the same way of a POST call and then i process it in order to build the desired URL.
This is my Ajax.js file:
const ajaxRequest = (config) => {
const token = TokenStorage.get()
config.baseURL = '/ajax'
if (token) {
config.headers = {
'Authorization': 'Bearer ' + token
}
}
return Axios.request(config)
}
const Ajax = {
get: (endpoint, params = null, config = {}) => {
const querystring = require('querystring')
let url = endpoint
if (Array.isArray(params) && params.length) {
url += '?' + params.join('&')
} else if (typeof params === 'object' && params !== null && Object.keys(params).length) {
url += '?' + querystring.stringify(params)
}
config = {
...config,
...{
url: url,
method: 'get'
}
}
return ajaxRequest(config)
},
post: (endpoint, params, config = {}) => {
config = {
...config,
...{
url: endpoint,
method: 'post',
data: params
}
}
return ajaxRequest(config)
}
}
I know that I could pass this data by POST but, in order to follow restful design, i want to keep GET method and optional params can be included in the URL as GET params.
If it were me I'd build a JavaScript array then call JSON.stringify() on it... then URL encode the resultant string and attach it as the sole parameter... to be JSON parsed by your server side handler.
I'm in a similar situation and I couln't find a built in library for this.
the most elegant solution I've found so far is by adding
Array.prototype.encodeURI = function(name) {
prefix = `${name}[]=`;
return prefix + this.map(o => encodeURI(o)).join(`&${prefix}`);
}
now you can use it:
let subjects = ["First Subject", "Second Subject"];
let myquery = subjects.encodeURI("subjects")
console.log(myquery)
// 'subjects[]=First%20Subject&subjects[]=Second%20Subject'
Note:
For empty arrays (e,g: let arr = [];) this method responds with subjects[]=, which php reads as an array with a single empty string (e,g: print_r($_REQUEST["subjects"]) prints Array ( [0] => )).
I couldn't find a standard for sending empty arrays url encoded and you should handle that somewhere.

How to Filter JSON.parse results

I have been trying to filter the results of an API call based on my "note" value. I've been building it on Zapier and the call works but I cannot seem to find a way to make a filter function do its job (so if I replace line 19-23 with return results; then it gives me all orders from the api call). I've poured over every stack document I could find but they all end with the error result.filter not found, or a bargle error (generic error in Zapier).
const options = {
url: `https://mystorename.myshopify.com/admin/orders.json?`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
var results = z.JSON.parse(response.content);
var queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem);
return filteredOrders;
});
And this is an example of my current output with return results; and no filter:
{
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
Again the goal is to filter by the value in the "note" key. So if my filter input is 555-5555 then it should return all information for that item only. I did try to use an if statement for return, stringify instead of parse, covert to array...all with needed code, but regardless of the format I find filter does not work or nothing is returned. Going to keep working on it, so if I happen to find the answer I will post that, but at this point I feel stuck.
You are trying to use the method filter in a object but filter is only available in an array so you should try to call filter in the orders array.
let results = {
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
let queryItem = "555-5555";
let newArray = results.orders.filter(function (item) {
return item.note == queryItem
})
console.log(newArray)
Updated to contain a real http call:
const url = 'http://www.mocky.io/v2/5d9466142f000058008ff6b7'
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
const response = await fetch(url, options)
const results = await response.json()
const queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem)
console.log(filteredOrders)
You are trying to filter on results, but according to your output, you should be filtering on results.orders.
const filteredOrders = results.orders.filter(item => item.note === queryItem);
Are you getting all the orders back (all the orders with the specified filter value)?
I realized I wasn't getting back all orders and this did the trick:
`https://mystorename.myshopify.com/admin/orders.json?status=any`
Alternatively, you can query the orders with that specific note:
`https://mystorename.myshopify.com/admin/orders.json?status=any&note=` + queryItem

$_POST does not detect the formData passed from ajax

Using redux-api-middleware which works similarly to axios and jquery.ajax, I passed a formData which is a mixture of an image and other form values as you can see on this image:
The problem I have is that after successfully calling the API via a POST request, the PHP $_POST object is null though there was an actual POST request happening. This is my code snippet:
import { CALL_API } from "redux-api-middleware";
export function createTestAnnouncement(data) {
return (dispatch, getState) => {
const { auth: { oauthToken, oauthTokenSecret } } = getState();
const formData = new FormData();
Object.entries(data).forEach(([key, value]) => {
if (key === 'image') {
formData.append(key, value);
} else {
formData.set(key, value);
}
});
return dispatch({
[CALL_API]: {
endpoint: "/api/test-announcements",
method: "POST",
headers: {
'xoauthtoken': oauthToken,
'xoauthtokensecret': oauthTokenSecret,
},
body: formData,
types: [CREATE_TEST_ANNOUNCEMENTS, CREATE_TEST_ANNOUNCEMENTS_SUCCESS, CREATE_TEST_ANNOUNCEMENTS_FAILURE]
}
})
}
}
How will be able to get values from the $_POST object? Did I use the FormData object correctly?
EDIT: My Controller is just this, PS: I am sure this working because this is working on a plain application/json request
use api\controllers\BaseController;
use model\Operations\TestAnnouncements\TestAnnouncementOperation;
use model\DB\TestAnnouncement;
class IndexController extends BaseController
public function actionCreate()
{
var_dump($_POST);
// Commented this out because the payload is not JSON
// $request = \Yii::app()->request;
// $op = new TestAnnouncementOperation();
// $op->topic = $request->getJSON('topic');
...
}
...
I always get a NULL on my var_dump. While using postman and passing form-data on the body generates me a value on my $_POST.
you can check if the variable is set or not using...
if(!isset($_POST["ur_varible_name_from_html_form"]))
{
echo "error";
}
You can see redux-api-middleware repo on github, issues #125. They already have resolved and given example [CALL_API] and [RSAA] with from data.

Categories