Passing query param to api in Angular - javascript

I have a child component, in which, after button press it pass a form field to a father component. I have to pass this fields as query Params to an API GET /valuation/ that require more or less 20 optional parameters, in which the name differs from Input fields.
I created a temporary object res inside the father function accept in which I iterate the field . Still I can't figure how to pass this parameter inside the object res, using multiple if is dirty code.
for example
Function in father component
accept(form:any){
const req: any = {};
if(form.name)
req.user = form.name
if(form.address)
req.clusterAddress = form.address
... and so on x 20 times
this.requestService.getRequest(req).subscribe(
(response) => {
this.getRequest(response);
}, (error) => {
console.error(error);
}
}
As you can see this is not a viable option, what I can use to take dynamically the query param names?

You can use a map to store information about which property from the form maps to which property on your res object and then iterate through the keys, check for the presence of the value and assign:
const formToResMap: { [key: string]: string } = {
name: 'name',
address: 'clusterAddress',
// ...
};
accept(form: any) {
const req = Object.keys(formToResMap).reduce((acc, key) => {
if (form[key]) {
acc[formToResMap[key]] = form[key];
}
return acc;
}, {});
console.log(req);
}

Related

Resolve two GraphQL schema fields using one endpoint

There's a situation where there are two possible types to fill data property. I have made a union type for that (ComponentItem) to determine which field needs to be returned. The first schema (ComponentItem1) should just be a hardcoded list but the second one (ComponentItem2) is more dynamic where it gets a searchTerm from query and it actually calls an endpoint to fill the list and also has hasNextPage property.
Here are the schemas I made:
type Component {
id
title
data: ComponentItem
}
union ComponentItem = ComponentItem1 | ComponentItem2
type ComponentItem1 {
list: [List!]!
}
type ComponentItem2 {
hasNextPage: Boolean;
list: [List!]!
}
In the resolver I'm resolving the union type in order to generate proper __typename:
const resolver: {
ComponentItem: {
__resolveType(object) {
if(object.searchTerm){
return "ComponentItem2"
}
return "ComponentItem1"
},
},
}
What I'm currently doing is to resolve the list and hasNextPage individually but in this scenario I'm sending the request to the same endpoint twice.
const resolver = {
...resolver,
ComponentItem2: {
list: async (root, __, context) => {
const result = await fetch('search-endpoint')
return result?.items || []
}
hasNextPage: async (root, __, context) => {
const result = await fetch('search-endpoint')
return result?.hasNextPage || false
}
}
}
My question is how it is possible to share that result in another field resolver (Other than using "context"). Or if there's any better way to handle this situation let me know.

Trying to get a value from a custom store Svelte

i want to ask something, i have a custom store like
const BlaBla = (Data) => {
const { subscribe, set, update } = writable(Data);
return {
subscribe,
update,
set,
setData: (NewData) => {
set(NewData)
},
getData: () => {
return <<<<<<< "Here lies the problem, how i can get the "newData"?."
}
}
}
i will explaying the scenario, im creating a script for a fivem server and im using svelte, i create a store that get a Vehicle with some properties like Name, Last Name, Plate and bla bla, i create the setData(Vehicle) and pass a set(Vehicle) then in another method i want to "get" the plate only, one solution i did was creating a variable in the scope and instead of a set i did an update like this
const VehicleStore = (Vehicle) => {
let Data = {} //Variable inside the scope
const { subscribe, set, update } = writable(Vehicle);
return {
subscribe,
update,
set,
setData: (NewData) => {
update((s) => {
s = NewData
Data = s
return s
})
},
getData: () => {
return Data.Plate
}
}
}
i don't know if this is the actual solution, i think im missing something
Svelte exports a get function that can be used to resolve the value of a store once (it is syntactic sugar around subscribe).
So first you have to get the value of the store, then you can access its property:
import { get } from 'svelte/store';
// ...
const store = writable(Data);
const { subscribe, set, update } = store;
// ...
return get(store).Plate
Note that accessing data like this will not be reactive because there is no persistent subscription to the store. You are generally not meant to use stores like that.
Instead you usually would use the store in a component's markup using auto subscriptions via $:
$VehicleStore.Plate

Javascript, in a React application assign to {} in a function component, code review

I have this code in a friend of mine React application and I need to understand what this code does explicitly:
const Component = ()=> (
<QueryFetcher>
{({ data }) => {
const { user: { profile = {} } = {} } = data
return (
<div>
{profile.username && profile.username}
</div>
)
}}
</QueryFetcher>
)
What is this line for?
const { user: { profile = {} } = {} } = data
Is it correct to assign something to {} using { user: { profile = {} } = {} } in this functional component? Or in a render() hook of a stateful component in React?
const { user: { profile = {} } = {} } = data basically means that your retrieving the user profile.
const means that you are creating a new variable
{ user: { profile } } } means that you are retrieving profile inside of user
= {} means that if the object is undefined, use an empty object so it will not fail because doing user.profile will throw an error if user is undefined.
= data means that you retrieving this info from the data variable
So, this line means, from the variable data, go take the user, if the user is undefined, use an empty object. Then, go take the profile, if the profile is undefined, use an empty object. Then create a variable called profile with the result. This is like doing this:
const user = data.user === undefined ? {} : data.user;
const profile = user.profile === undefined ? {} : user.profile;
What is this line for?
const { user: { profile = {} } = {} } = data
It's basically just chained ES6 object-destructuring with default values.
What this line does in words:
Read "user" from "data", if "user" is undefined, assign {} as a default value
Read "profile" from "user", if "profile" is undefined, assign {} as a default value
Is it correct
It is mostly a short-hand syntax used to remove repetitive stuff. So instead of accessing multiple object props separately e.g.
this.props.prop1, this.props.prop2, ...
you can use
const { prop1, prop2 } = this.props;
It also helps other readers later quickly understanding what variables are used in a method if all necessary props are destructured at the start.

Using Variables with react-apollo Query

I've attached a query to my React Native component like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash(geoHash: "8k"){
id
}
}`;
export default graphql(getNearbyStoriesQuery,
{
props: (props) => {
debugger;
let storiesNearby = props.data.getStoriesNearbyByGeoHash.map((story) => {
return {
id: story.id,
}
});
return {storiesNearby};
},
variables: {
geoHash: mockGeoHash
}
})(Home); // Home is the React Native Component
I'm able to retrieve data from using this technique as long as I hardcode a value in for geoHash in the query; in this case I used "8k". However, when I attempt to modify the query so that I can puss in a variable like so:
let getNearbyStoriesQuery = gql`{
getStoriesNearbyByGeoHash($geoHash: String!){
id
}
}`;
I get an error saying Expected Name, found $. This method of passing variables to queries is repeated across multiple sources. What am I doing wrong here?
Should be:
query GetStoriesNearbyByGeoHash($geoHash: String!) {
getStoriesNearbyByGeoHash(geoHash: $geoHash){
id
}
}
Have a look on how to use variables in graphql: http://graphql.org/learn/queries/#variables

How can I use variables as field names in POST/PATCH request body in Javascript?

async onSubmitConditionDuration() {
var param = (this.state.health_condition+"_personal_age")
try {
axios.patch(URL,
{
param: this.state.condition_duration, //param is a variable that represents a field name at the endpoint(URL)
})
.then((response)=>{
console.log(response.status);
})
.catch((errors) => {
console.log(errors);
})
}
catch(errors){
console.log(errors);
}
}
I'm trying to have field names as variable in the json body of
my request so that fields can be dynamically updated based on variables' values.
By using the above syntax ,the patch request fails to update the field represented by the value stored in 'param'.
How can this be done in Javascript?
I'm working in a react native app
You can use the [] syntax:
var param = (this.state.health_condition+"_personal_age")
var object = {
[param]: this.state.condition_duration,
}

Categories

Resources