querying stripe api & display image - reactjs

I have been following a tutorial to query Stripe API and display data. One thing that is not mentioned is how to query the images and display it. I can see from the structure that the images property is there but I need some help to display it. I assume it should be the same logic how it is displaying the product name but I just need to understand to follow the same logic for the images.
Here is my query, I have added the image option in my query:
and can see the result in GrapiQL:
Here is example of how I am mapping over my products to display correctly. From what I understand I need to do the same for the image. I have followed the same logic by just replacing product with image but just can't seem to get it working. Here is the snippet:
const Products = () => {
return (<StaticQuery query={PRODUCTS_QUERY}
render={
({ allStripeSku, allStripeProduct }) => {
return allStripeProduct.edges.map(product => {
const skus = allStripeSku.edges.filter(
sku => sku.node.product.id === product.node.id
)
return (
<Product
key={product.node.id}
skus={skus}
product={product.node} />
)
})
return
}
}
/>)
}
Can anyone please point my in the right direction so I can get this working?

You need to add 2 lines of code:
in GraphQL query to return images alongside id and name as you've already done
in ProductCard component to return an <img> element using the query field added above
For me this meant adding the + lines below:
in src/components/Products/Products.js
in src/components/Products/ProductCard.js
I assume it's the Gatsby E-commerce Tutorial you were following; if so please be aware that, since your OP, they've updated the docs so it no longer uses the deprecated Orders API.

Related

Algolia: Export React Instant Search results

Is there any way to export Algolia's React Instant Search results to a CSV? I've tried using the react-csv package, but it doesn't work with Algolia's Hit Component. The package requires data as props, but the data is constantly changing since it's React Instant Search.
What I mean by constantly changing is that on page load, you're given the entire index of records found, then you can narrow down the results with the search bar or other filtering components.
I've gone down the Google rabbit hole looking for information about exporting Algolia's search results as a CSV, but I haven't found anything regarding React Instant Search—unless I completely missed it.
Has anyone tried this before? If so, could you point me in the right direction regarding documentation or examples?
Not sure if this solves your problem but one possible way is to use the StateResults widget. The StateResults widget provides a way to access the searchState and the searchResults of InstantSearch.
Here I will create a custom StateResults component in the form of a download button and then connect it using the connectStateResults connector.
I have attached a demo below as well.
For simplicity I didn't format the data to be fed into the CSV builder.
// 1. Create a React component
const StateResults = () => {
// return the DOM output
};
// 2. Connect the component using the connector
const CustomStateResults = connectStateResults(StateResults);
// 3. Use your connected widget
<CustomStateResults />
In your case something like
const StateResults = ({ searchResults }) => {
const hits = searchResults?.hits;
return (
<div>
<button>{hits && <CSVLink data={hits}>Download CSV</CSVLink>}</button>
</div>
);
};
const DownloadButton = connectStateResults(StateResults);
//in your JSX then <DownloadButton />

Material UI - Google Maps Autocomplete - Restrict to city and state?

I'm using the Google Maps Places Autocomplete that comes with Material UI and I'm stuck on trying restrict the results. When a user starts typing the only suggestions I want returned are City, State for them to select.
Here is a link to MUI's documentation with example:
Material UI - Google Places Autocomplete
Thanks!
It looks like the code from the library is using the AutocompleteService.getPlacePredictions. To achieve your use case you need to include the types properties with value of ['(cities)'] to your AutocompleteService.getPlacePredictions request. This will instructs the Places service to return results that match locality or administrative_area_level_3 as stated here
You can add it inside the fetch in the code sample just like below:
fetch({ input: inputValue, types: ['(cities)'] }, (results) => {
if (active) {
let newOptions = [];
if (value) {
newOptions = [value];
}
if (results) {
newOptions = [...newOptions, ...results];
}
setOptions(newOptions);
}
});
Here's the sample code. Make sure to use your API key for the sample to work.

how to avoid nested document's property assignment that results in undefined

This is how my incoming object from server looks like:
{
"name":"product1",
"categories": {
"cat1": {
"supported": false
},
"cat2": {
"supported": true
}
}
When the page loads, I will have 100s of categories and I populate categories object based on which category user selects. Those categories that were not selected by the user, don't exist in the product object.
When user is trying to edit the product, I have to show all the 100 categories in the checkboxes and show those categories checked which as supported set to true.
This is how my checkbox looks like:
data.props.categories.map((category, index) =>
<Form.Checkbox defaultChecked={productData.categories[category._id].supported} label={category.displayname}></Form.Checkbox>
);
This throws me an error saying when a category does not exist in product object because I am trying to access supported property of an undefined object. I am able to achieve what I need by writing a function that checks if a particular category exists in the incoming products object or not.
const isCategorySupported = (category_id) => {
debugger
if (productData.categories.hasOwnProperty(category_id)) {
return productData.categories[category_id].supported
}
return false
};
<Form.Checkbox defaultChecked={isCategorySupported(category._id)} label={category.displayname}></Form.Checkbox>
I was wondering if there is a better way or react way of doing this without writing a function?
Your solution looks fine. You may use optional chaining for this if you want a more elegant way:
<Form.Checkbox
defaultChecked={productData?.categories?.[category_id]?.supported}
label={category.displayname}>
</Form.Checkbox>
You have to keep in mind that this is not natively supported in the browsers just yet so a babel setup will be needed for this.
You are trying to map through categories object. So, you should be able to do like:
Object.keys(data.props.categories).map((category, index) =>
<Form.Checkbox defaultChecked={data.props.categories[category].supported} label={data.props.categories[category].displayname}></Form.Checkbox>
);

ReactJs : How to print data from console to web-page?

After a successful POST and GET query, the results of my operation are visible in the console of my React Dev Tools. How should I take those results, preferable create a table and render that table on my web-app itself?
Here is the GET request :
axios.get('http://localhost:5000/result')
.then((response) => {
console.log(response);
});
}
The format of results displayed on console is like this :
Let's say I want to create a table by traversing through the results with headers _id and Name. I know I should use the map function. But exactly where and how should I do that in my code?
You have a few options. You can make your call in componentDidMount, set the result in a state and then render that state.
componentDidMount() {
axios.get('http://localhost:5000/result')
.then((response) => {
this.setState({
data: response // maninpulate your response here
})
});
}
}
render() {
const { data } = this.state;
return this.renderTable(data) // this should return a table
}
Assuming you know the concept of 'useState' in react hooks. If not please have an understanding of it.
Long story short, useState is used to store the data in variables.
const [data, setData] = useState();
Instead of console.log(response); you set the response to the variable i.e; setData(response);
In html,
<table>
//some headers, if needed
//This will iterate your array of objects
{data.map((eachData) => (
<tr> <td>{eachData.id}</td>
<td>{eachData.name}</td>
....
</tr>
)
</table>
Please Note: The HTML part works for both class-based and function-based React components where as 'useState' is part of React hooks functionality, works only for function-based components.
I have created a small sample app where I have used react-table for displaying the data as a table. Also In this example I have added promise in order to simulate server fetching data from server. This you can replace with actual server call i.e., axis.get etc.
React-table provides a lot many features that might be helpful. Such as you can provide which columns you wish to display out of all the columns from the data.
If you do not wish to use any library for displaying table, that is also possible only that you have to replace ReactTable with your custom table implementation.
Hope this helps.
Thanks to this page: https://www.skptricks.com/2019/02/can-you-consolelog-in-jsx.html.
You can do console.log in the render function of a class component or in the return statement of a function component. In your case:
function Foo(props){
data = axios.get('http://localhost:5000/result')
return(
<>
{console.log(data)}
</>)
}
In my opinion, it's much more straight forward than the other state methods.

React-select auto loading options

This if my first question on SO so hopefully I dont forget anything.
I am currently developing a site with React that allows the customer to type in the first few letters of a vehicle name and it searches the database bringing back results. I am also accessing this site directly from another site via react-router and an iframe.
When I am coming in from the external site, I will be passing a query to react-router. The query will come in something like:
http://localhost:9292/#/?id=362789&start=1446015600000&stop=1446101999999
I would like react-select to automatically getOptions if "id" was included in the query. Otherwise I would like it to continue to wait for user input as it is working now.
My current code looks something like. I know I will need a if/else statement but more concerned with the auto-loading factor for now:
render() {
const asset_id = this.props.id
const getOptions = (input) => {
return fetch(`/subject?q=${input}`, {credentials: 'include'})
.then((response) => {
return response.json();
}).then((data) => {return {options: data}});
}
return (
<div className="picker">
<Select.Async
loadOptions={getOptions}
minimumInput={2}
value={this.state.selectValue}
onChange={this.updateValue.bind(this)}
ref="dropdown"
name="chooser"
/>
</div>
}
Any help you could give would be wonderful. Im still getting familiar with React and I feel I am overlooking something simple possibly.

Resources