Display image with react from strapi - javascript

i have a problem with fetching images from strapi .
i tried a lot but it wont show any images , also when i post rich text ad try image it wont work, can somebody help me out !
const ApiUrl = ('http://localhost:1337')
const { id } = useParams()
const {loading , error , data } = useFetch('http://localhost:1337/reviews/ ' + id)
if(loading) return <p>Loading..</p>
if(error) return <p>Error</p>
return (
<div className={classes.root}>
<div className={classes.container}>
<img src={ApiUrl + data.image} alt={data.naam} />
<h2 className={classes.headertxt}>{data.naam}</h2>
also tried {review.image} {data.image.url} review.image.url
regardss

I think you need to check the documentation for your API (if you use rest API) or schema of GraphQl playground (if you use GrapQl).
Install Swagger UI documentation plugin to check schema.
This may fix your problem.

Maybe this can give you some directions.
LINK TO STRAPI CONTENT API GET
and this is what this should return for you:
{
"id": 1,
"title": "Restaurant 1",
"cover": {
"id": 1,
"name": "image.png",
"hash": "123456712DHZAUD81UDZQDAZ",
"sha256": "v",
"ext": ".png",
"mime": "image/png",
"size": 122.95,
"url": "http://localhost:1337/uploads/123456712DHZAUD81UDZQDAZ.png",
"provider": "local",
"provider_metadata": null,
"created_at": "2019-12-09T00:00:00.000Z",
"updated_at": "2019-12-09T00:00:00.000Z"
},
"content": [
{
"__component": "content.title-with-subtitle",
"id": 1,
"title": "Restaurant 1 title",
"subTitle": "Cozy restaurant in the valley"
},
{
"__component": "content.image-with-description",
"id": 1,
"image": {
"id": 1,
"name": "image.png",
"hash": "123456712DHZAUD81UDZQDAZ",
"sha256": "v",
"ext": ".png",
"mime": "image/png",
"size": 122.95,
"url": "http://localhost:1337/uploads/123456712DHZAUD81UDZQDAZ.png",
"provider": "local",
"provider_metadata": null,
"created_at": "2019-12-09T00:00:00.000Z",
"updated_at": "2019-12-09T00:00:00.000Z"
},
"title": "Amazing photography",
"description": "This is an amazing photography taken..."
}
],
"opening_hours": [
{
"id": 1,
"day_interval": "Tue - Sat",
"opening_hour": "7:30 PM",
"closing_hour": "10:00 PM"
}
]
}

Related

How to flatten React state of comment section?

This is my data:
{
"currentUser": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-amyrobson.png",
"webp": "/src/assets/images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-maxblagun.png",
"webp": "/src/assets/images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-ramsesmiron.png",
"webp": "/src/assets/images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
}
]
}
]
}
and this is how i'd want it to look like, each comment to store the replies id's
{
"currentUser": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
},
"comments": [
{
"id": 1,
"content": "Impressive! Though it seems the drag feature could be improved. But overall it looks incredible. You've nailed the design and the responsiveness at various breakpoints works really well.",
"createdAt": "1 month ago",
"score": 12,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-amyrobson.png",
"webp": "/src/assets/images/avatars/image-amyrobson.webp"
},
"username": "amyrobson"
},
"replies": []
},
{
"id": 2,
"content": "Woah, your project looks awesome! How long have you been coding for? I'm still new, but think I want to dive into React as well soon. Perhaps you can give me an insight on where I can learn React? Thanks!",
"createdAt": "2 weeks ago",
"score": 5,
"user": {
"image": {
"png": "/src/assets/images/avatars/image-maxblagun.png",
"webp": "/src/assets/images/avatars/image-maxblagun.webp"
},
"username": "maxblagun"
},
"replies": [ 3, 4 ]
},
{
"id": 3,
"content": "If you're still new, I'd recommend focusing on the fundamentals of HTML, CSS, and JS before considering React. It's very tempting to jump ahead but lay a solid foundation first.",
"createdAt": "1 week ago",
"score": 4,
"replyingTo": "maxblagun",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-ramsesmiron.png",
"webp": "/src/assets/images/avatars/image-ramsesmiron.webp"
},
"username": "ramsesmiron"
}
},
{
"id": 4,
"content": "I couldn't agree more with this. Everything moves so fast and it always seems like everyone knows the newest library/framework. But the fundamentals are what stay constant.",
"createdAt": "2 days ago",
"score": 2,
"replyingTo": "ramsesmiron",
"user": {
"image": {
"png": "/src/assets/images/avatars/image-juliusomo.png",
"webp": "/src/assets/images/avatars/image-juliusomo.webp"
},
"username": "juliusomo"
}
}
]
}
So far I've used the data as it was, and I had a hard time setting the state later, and after reading the react docs (https://beta.reactjs.org/learn/choosing-the-state-structure#avoid-deeply-nested-state) I understood why it was so hard to manage. But the docs don't have any methods on how to flatten it
While for huge lists this is really not advisable, you can still do something like this
const replies = [];
// commentData is your incoming data
const data = {...commentData,
comments: commentData.comments.map(comment => {
if(comment.replies.length) {
comment.replies = comment.replies.map(reply => {
replies.push(reply);
return reply.id;
})
}
return comment;
})
};
data.comments = data.comments.concat(replies);
Remember that this is not very flexible in cases where replies might again have comments/replies ( nested objects )
JS Fiddle - https://jsfiddle.net/7d61jsm3/

Google Sheets not receiving json data properly from Woocommerce Webhook

I hope you guys are having a wonderful day.
I have set up a webhook in my woocommerce that sends JSON data to Google sheets. The webhook has been working great for months now, just today, I am having some trouble with it. I have tracked the issue to be in google sheets receiving the JSON data, but I don't know why this is happening.
Let me explain.
https://docs.google.com/spreadsheets/d/18G-yVDjYeccl6kznpZgSuRTysRMAu57pwY2oGf6-KWI/edit?usp=sharing
This is the google sheet, when it gets Woocommerce JSON data, it populates a new row.
The problem
Sometimes google sheets doesn't populate the row upon receiving a new order. The problem doesn't lie with woocommerce, because I have checked woocommerce with reqbin and the webhook fires with every order.
Furthermore, when I send requests from reqbin.com to my sheet, the sheet performs the operation successfully 5-6 out of 10 times. Other times it shows an error.
The Error
The error is due to google sheets not being able to parse JSON data, because the JSON data it receives 5 out of 10 times is not proper JSON data. Other 5 times, it is just as it should be. I have put a catch statement if the sheet is unable to parse JSON. Instead of appending new row with the parsed data, it appends the raw received data to the sheet.
It is clear now that there is some issue with google sheets handling that JSON data because when the same data is sent from reqbin.com to webhook.site, it is perfectly as it should be 10/10 times.
How to reproduce the issue
Open this google sheet. https://docs.google.com/spreadsheets/d/18G-yVDjYeccl6kznpZgSuRTysRMAu57pwY2oGf6-KWI/edit?usp=sharing
Open reqbin.com and webhook.site, and send the following JSON from reqbin.com to webhook.site 10 times to see if any kind of error occurs.
{ "id": 47222, "parent_id": 0, "status": "processing", "currency": "PKR", "version": "5.1.0","prices_include_tax": false, "date_created": "2021-06-10T01:23:46", "date_modified": "2021-06-10T01:23:46", "discount_total": "0", "discount_tax": "0", "shipping_total": "150", "shipping_tax": "0", "cart_tax": "0", "total": "1850", "total_tax": "0", "customer_id": 0, "order_key": "wc_order_7gIuR7px6MX9C", "billing": { "first_name": "Name", "last_name": "", "company": "", "address_1": "Address", "address_2": "", "city": "City", "state": "", "postcode": "", "country": "PK", "email": "email#email.com", "phone": "1234" }, "shipping": { "first_name": "Name", "last_name": "", "company": "", "address_1": "Address", "address_2": "", "city": "City", "state": "", "postcode": "", "country": "Country" }, "payment_method": "cod", "payment_method_title": "Cash on delivery", "transaction_id": "", "customer_ip_address": "8.8.8.8", "customer_user_agent": "Mozilla/5.0 (Linux; Android 11; M2102J20SG) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.88 Mobile Safari/537.36", "created_via": "checkout", "customer_note": "", "date_completed": null, "date_paid": null, "cart_hash": "64d834c72eecc8e32b9d83fd67d10d9c", "number": "47222", "meta_data": [ { "id": 869388, "key": "_shipping_calculator", "value": "" }, { "id": 869389, "key": "is_vat_exempt", "value": "no" }, { "id": 869391, "key": "_wfacp_report_data", "value": { "wfacp_total": "0.00" } }, { "id": 869392, "key": "_woofunnel_cid", "value": "4" }, { "id": 869393, "key": "_wfacp_post_id", "value": "24852" }, { "id": 869394, "key": "_wfacp_source", "value": "https://website.com/checkouts/checkout-page/" }, { "id": 869395, "key": "_wfacp_timezone", "value": "Asia/Karachi" }, { "id": 869396, "key": "order_comments", "value": "" }, { "id": 869412, "key": "_new_order_email_sent", "value": "true" }, { "id": 869424, "key": "_woofunnel_custid", "value": "4" }, { "id": 869425, "key": "_pys_purchase_event_fired", "value": "1" }, { "id": 869426, "key": "_wfob_stats_ids", "value": [] }, { "id": 869427, "key": "_wfocu_thankyou_visited", "value": "yes" } ], "line_items": [ { "id": 35114, "name": "MTECH Ultra Resilient Knife", "product_id": 11074, "variation_id": 0, "quantity": 1, "tax_class": "", "subtotal": "1700", "subtotal_tax": "0", "total": "1700", "total_tax": "0", "taxes": [], "meta_data": [], "sku": "", "price": 1700, "parent_name": null } ], "tax_lines": [], "shipping_lines": [ { "id": 35115, "method_title": "Fast Shipping (2-4 Days)", "method_id": "flat_rate", "instance_id": "1", "total": "150", "total_tax": "0", "taxes": [], "meta_data": [ { "id": 275053, "key": "Items", "value": "MTECH Ultra Resilient Knife × 1", "display_key": "Items", "display_value": "MTECH Ultra Resilient Knife × 1" } ] } ], "fee_lines": [], "coupon_lines": [], "refunds": [], "date_created_gmt": "2021-06-09T20:23:46", "date_modified_gmt":"2021-06-09T20:23:46", "date_completed_gmt": null, "date_paid_gmt": null, "currency_symbol": "₨","_links": { "self": [ { "href": "https://website.com/wp-json/wc/v3/orders/47222" } ],"collection": [ { "href": "https://website.com/wp-json/wc/v3/orders" } ] } }
Now send the same data to the following google sheet to see if it appends the row correctly each time.
https://script.google.com/macros/s/AKfycbxupm9bje86F4PQQkyys_LWtXs_kj279R0ipgnZ-cLd7aiEADf1AN_prhk28vOPW9JsRQ/exec
How do I solve the issue? Please let me know if you need any more information. Thanks.
Edit:
Instead of getting a full JSON body like mentioned above, the google sheets seems to be getting the following JSON.
{contextPath=, queryString=, parameter={}, postData=FileUpload, parameters={}, contentLength=3981.0}
I would like to know why the google sheets default parameter (e) contains this instead of a full JSON body sent to it.
Edit # 2
I would like to know why the google sheets default parameter (e) contains this instead of a full JSON body sent to it.
This is because (e) has a body which will always contain those parameters. The error is due to Google Sheets receiving an empty JSON body. I am still unable to understand why this happens. When I send the same JSON to API testing sites, they always receive full JSON body. Google sheets, in some cases, does not. Why is that?
I managed to solve the issue with some trial and error. For anyone facing the same issue in the future, here is what worked for me.
I was using e.postData.contents to get the JSON body but this seems to have stopped working, which was causing the JSON body to be empty. I tried e.postData.getDataAsString(); which seems to be working just fine and the issue has been resolved.

I am using Jest to run some test in React. But when I run the test I receive the error " Cannot read property 'dateTime' of undefined

I have multiple test in my file but I will use the first one as an example.
import React from 'react';
import { shallow } from 'enzyme';
import Event from '../Event';
import { mockData } from '../mock-data';
describe('<Event /> component', () => {
let EventWrapper;
beforeAll(() => {
EventWrapper = shallow(<Event event={mockData} />)
})
test('rendered event container', () => {
expect(EventWrapper.find('.event-container')).toHaveLength(1);
});
})
Then here is my React Component file
import React, { Component } from 'react';
class Event extends Component {
state = {
showingDetails: false
}
eventDetails = () => {
const showingDetails = this.state.showingDetails;
if (showingDetails === false) {
this.setState({
showingDetails: true
})
} else {
this.setState({
showingDetails: false
})
}
};
render() {
const { event } = this.props;
const eventISODateTime = new Date(event.start.dateTime);
const eventDate = eventISODateTime.toDateString();
const eventTime = eventISODateTime.toTimeString();
const eventTimeFormatted = `${eventTime.slice(0, 5)} ${eventTime.slice(18)}`;
return <div className="event-container">
<h1 className="event-summary">{event.summary}</h1>
<p className="event-date">{eventDate} </p>
<p className="event-time">{eventTimeFormatted}</p>
<p className="event-location">{event.location}</p>
{this.state.showingDetails && (
<div className="event-details">
<h3 className="about-event">About event:</h3>
<a className="details-link" target="_blank" rel="noreferrer" href={event.htmlLink}>See details on Google Calendar</a>
<p className="event-description">{event.description}</p>
</div>
)}
<button className="show-hide" onClick={() => this.eventDetails()}> {this.state.showingDetails ? 'hide description' : 'show description'} </button>
</div >
}
}
export default Event;
I defined dateTime inside of the render().
I using the same { mockData } for each file . When I load my site either in localhost or on Github gh-pages it works fine and displays the data correctly, so it is just giving me an error when running the test 'npm run test'
Here is the mockData file I am pulling from
const mockData = [
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200519T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MTlUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-19T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-19T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181159875584000\"",
"id": "3qtd6uscq4tsi6gc7nmmtpqlct_20200520T120000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=M3F0ZDZ1c2NxNHRzaTZnYzdubW10cHFsY3RfMjAyMDA1MjBUMTIwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:14:30.000Z",
"updated": "2020-05-27T11:45:37.792Z",
"summary": "React is Fun",
"description": "Love HTML, CSS, and JS? Want to become a cool front-end developer? \n\nReact is one of the most popular front-end frameworks. There is a huge number of job openings for React developers in most cities. \n\nJoin us in our free React training sessions and give your career a new direction. ",
"location": "Berlin, Germany",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-20T15:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "3qtd6uscq4tsi6gc7nmmtpqlct",
"originalStartTime": {
"dateTime": "2020-05-20T14:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "3qtd6uscq4tsi6gc7nmmtpqlct#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
{
"kind": "calendar#event",
"etag": "\"3181161784712000\"",
"id": "4eahs9ghkhrvkld72hogu9ph3e_20200521T140000Z",
"status": "confirmed",
"htmlLink": "https://www.google.com/calendar/event?eid=NGVhaHM5Z2hraHJ2a2xkNzJob2d1OXBoM2VfMjAyMDA1MjFUMTQwMDAwWiBmdWxsc3RhY2t3ZWJkZXZAY2FyZWVyZm91bmRyeS5jb20",
"created": "2020-05-19T19:17:46.000Z",
"updated": "2020-05-27T12:01:32.356Z",
"summary": "Learn JavaScript",
"description": "Have you wondered how you can ask Google to show you the list of the top ten must-see places in London? And how Google presents you the list? How can you submit the details of an application? Well, JavaScript is doing these. :) \n\nJavascript offers interactivity to a dull, static website. Come, learn JavaScript with us and make those beautiful websites.",
"location": "London, UK",
"creator": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"organizer": {
"email": "fullstackwebdev#careerfoundry.com",
"self": true
},
"start": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"end": {
"dateTime": "2020-05-21T17:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"recurringEventId": "4eahs9ghkhrvkld72hogu9ph3e",
"originalStartTime": {
"dateTime": "2020-05-21T16:00:00+02:00",
"timeZone": "Europe/Berlin"
},
"iCalUID": "4eahs9ghkhrvkld72hogu9ph3e#google.com",
"sequence": 0,
"reminders": {
"useDefault": true
},
"eventType": "default"
},
];
export { mockData };

get values from JSON given by randomuser.me and loop through to append in divs

hoping to use randomuser.me in a prototype i'm putting together (html, css, jquery)
I need to use its api to access profile photos.
I've got this code puling in the JSON as they show in their documentation:
$.ajax({
url: 'https://randomuser.me/api/?results=5&gender=female',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
Now I need to get the url from the picture value in the JSON and write it to the background-image css of a group of divs...I imagine by creating some kind of loop, anybody have an easy to understand way of doing this?
the JSON returned looks like this:
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "romain",
"last": "hoogmoed"
},
"location": {
"street": "1861 jan pieterszoon coenstraat",
"city": "maasdriel",
"state": "zeeland",
"postcode": 69217
},
"email": "romain.hoogmoed#example.com",
"login": {
"username": "lazyduck408",
"password": "jokers",
"salt": "UGtRFz4N",
"md5": "6d83a8c084731ee73eb5f9398b923183",
"sha1": "cb21097d8c430f2716538e365447910d90476f6e",
"sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
},
"dob": "1983-07-14 07:29:45",
"registered": "2010-09-24 02:10:42",
"phone": "(656)-976-4980",
"cell": "(065)-247-9303",
"id": {
"name": "BSN",
"value": "04242023"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/83.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
"nat": "NL"
}
],
"info": {
"seed": "2da87e9305069f1d",
"results": 1,
"page": 1,
"version": "1.1"
}
}
If I've got right you need something like this:
$( ".myDivClass" ).each(function( index ) {
$( this ).attr("background-image", results[index].picture.medium));
});
Or if you have in results only one element of array so to do: ...results[0].picture.medium...

onedrive/ skydrive api - get file thumbnails

I am creating a file picker using the skydrive/onedrive api
I get a list of files using the url:
https://apis.live.net/v5.0/'+folder_path+'/files?access_token='+onedrive_access_token
But this doesn't return a thumbnail for the files (unlike other api's, googledrive for example).
I would like to get a thumbnail for each file, if it exists.
I cant find anywhere in the docs how to do this - is there a way I can?
After complete the call, you should get some result like this.
{
"data": [
{
"id": "[file id]",
"from": {
"name": "...",
"id": "..."
},
"name": "[file name]",
"description": "",
"parent_id": "[parent folder id]",
"size": 12345,
"comments_count": 0,
"comments_enabled": false,
"tags_count": 0,
"tags_enabled": true,
"is_embeddable": true,
"picture": "[thumbnail url] <<< this is what you want",
"source": "[public preview url]",
"upload_location": "...",
"link": "...",
"height": 270,
"width": 480,
"duration": 22443,
"bitrate": 802928,
"type": "video",
"shared_with": {
"access": "Just me"
},
"created_time": "2013-01-01T07:27:17+0000",
"updated_time": "2013-01-01T07:40:44+0000",
"client_updated_time": "2013-01-20T16:26:54+0000"
},
]
}
Which "picture" is the thumbnail url that you want.

Categories