Getting Image from api - reactjs

I have an api "https://www.pinkvilla.com/photo-gallery-feed-page/page/1" which returns response something like this.
"nodes": [
{
"node": {
"title": "PHOTOS: Shruti Haasan's Turkey vacay- A perfect mix of work and fun",
"nid_dont_use": "1",
"field_photo_image_section": "/files/styles/photogallery/public/shruti_haasan_in_turkey_main_0.jpeg?itok=ex_mE-AH",
"path": "/photos/shruti-haasan/photos-shruti-haasans-turkey-vacay-perfect-mix-work-and-fun-1184120",
"nid": "1184120",
"photo_image_nids": "1184114,1184115,1184116,1184117,1184118,1184119",
"ImageStyle_thumbnail": "/files/styles/imagestyle_1_1/public/shruti_haasan_in_turkey_main_0.jpeg?itok=44jwEbFY",
"last_update": "1661754431",
"views_count": "305",
"author_uid": "870656",
"author_name": "Pinkvilla Desk"
}
},
I am trying to get images from this api and I see two objects which have image path in it.
"ImageStyle_thumbnail": "/files/styles/imagestyle_1_1/public/shruti_haasan_in_turkey_main_0.jpeg?itok=44jwEbFY"
"field_photo_image_section": "/files/styles/photogallery/public/shruti_haasan_in_turkey_main_0.jpeg?itok=ex_mE-AH",
Is there any way I can get images from this api?

It seems like the pictures you're searching for can be composed by adding your API image url's to pinkvilla base url: https://www.pinkvilla.com/files/styles/photogallery/public/shruti_haasan_in_turkey_main_0.jpeg?itok=ex_mE-AH
You could try composing pinkvilla's base url with paths returned from your API, but it won't be a failsafe approach, as you can't possibly know if those images actually exists on pinkvilla's webserver.

You could do something like this to get the image URLs:
const [imageUrls, setImageUrls] = useState();
const fetchImages = async () => {
const baseUrl = "https://www.pinkvilla.com";
const result = await fetch(`${baseUrl}/photo-gallery-feed-page/page/1`).then((res) => res.json());
setImageUrls(result.nodes.map((node) => `${baseUrl}${node.node.field_photo_image_section}`));
};
fetchImages();
And then can use that array of URLs (imageUrl) to render the images using the <img src=""/> tag.

Related

How to modify value in data.json with react

I am trying to modify a value in my data.json. I am working on a web entertainment app for my portfolio
So I want to modify the value "isBookmarked" in my data.json
here it is a part of my data.json
type here{
"title": "Beyond Earth",
"thumbnail": {
"trending": {
"small": "./assets/thumbnails/beyond-earth/trending/small.jpg",
"large": "./assets/thumbnails/beyond-earth/trending/large.jpg"
},
"regular": {
"small": "./assets/thumbnails/beyond-earth/regular/small.jpg",
"medium": "./assets/thumbnails/beyond-earth/regular/medium.jpg",
"large": "./assets/thumbnails/beyond-earth/regular/large.jpg"
}
},
"year": 2019,
"category": "Movie",
"rating": "PG",
"isBookmarked": false,
"isTrending": true
},
with the IsBookmarded value I know which of the movies I did bookmark and I need to modify the value directly in json so after I can display only the bookmarked one and then toggle the one I don't want anymore in the bookmark section. But the thing I am trying to do with useEffect it's fetching the data, and make a copy of it and put that in a copy of the data with state but there is a problem
type hereconst [data, setData] = useState([]);
useEffect(() => {
axios.get("./data.json")
.then(res => setData(res.data))
.catch(err => console.error(err));
}, []);
function handleUpdateData(index){
const newData = [...data];
console.log(data[0].isBookmarked) // Here it's not working ,
// newData[index].isBookmarked = newData[index].isBookmarked ? false : true;
// setData(newData);
};
The problem it's that console.log(data) work and console.log(data[0]) work too
but if I want to do console.log(data[0].isBookmarked) the console is telling me that the
isBookmarded is not defined so I don't know what to do I am bit lost
In the frontend of React you cannot update the .json file directly. You can import (or fetch) the .json, store it on state, and manipulate the state - however the original .json file will remain in-tact.
If you want to be able to update the .json file, I would ask "why not use a simple datastore?" Look into Firebase / Firestore - very easy and fun to use - the entire store is JSON based and can be manipulated from your React frontend.
Otherwise you are looking into more complicated solutions which involved:
Sending a request to a backend server or cloud function
Using fs to write a file to the server to overwrite your .json file
Refreshing your client so that it loads the newly updated .json file
These 3 steps are much much more difficult than just using an actual database / datastore. MySQL, Postgres, Firestore are all options.
You can try this package which you will be able to send HTTP requests to the endpoint and update data.json

Expo MediaLibrary.getAssetsAsync({album:album}) is not returning album - React Native

I am using Expo MediaLibrary to get videos from a specific folder and I am facing this problem.
MediaLibrary.getAssetsAsync() shows there are no media inside an album. while there are media inside the folder.
Code:
let album = await MediaLibrary.getAlbumAsync("GrabTube")
console.log(album )
let assets = await MediaLibrary.getAssetsAsync({album:album })
console.log(assets)
response:
Object {
"assetCount": 1,
"id": "876214992",
"title": "GrabTube",
}
Object {
"assets": Array [],
"endCursor": "0",
"hasNextPage": false,
"totalCount": 0,
}
In the first console.log, it shows there is one item/asset inside the folder. But as shown inside the second console.log it shows the folder is empty.
Is there any fix for this?
For some reason it's necessary to define the mediaType even when you have already defined the album...
to me the solution was change from :
let assets = await MediaLibrary.getAssetsAsync({album:album })
to:
let assets = await MediaLibrary.getAssetsAsync({album:album, mediaType:'audio' })

Can you fetch data in next.config

Is there any way to fetch data within the next.config.js file, I am trying to set up i18n but would like for the locales array to be fetched from a CMS rather than statically input by the developer.
From Next.js docs: (https://nextjs.org/docs/api-reference/next.config.js/introduction)
next.config.js is a regular Node.js module, not a JSON file. It gets used by the Next.js server and build phases, and it's not included in the browser build.
It means that you can do something like this:
module.exports = {
async headers() {
const response = await fetch("https://example.com/langs");
const dt = await response.json();
return [
{
source: "/api/dashboard",
headers: [{ key: "Lang", value: dt.map((d) => d.lng).join(",") }],
},
];
},
};
Obviously the above code can be done inside the endpoint handler but I just wanted to give an example to prove it's working.

How to render Draft-js text in React from server

I using Draft-js to build my text-editor.
What I want to do is on clicking the submit button, the submitted text should appear on right side (as you can see, the blank side)
I'm calling a handleSubmit function to post the content to server:
handleSubmit = e => {
e.preventDefault();
const query = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()));
const payload = {
query:query
}
axios({
url:'http://localhost:9000/queries',
method:'POST',
data: payload
})
}
and to retrieve the content :
getQueries(){
axios.get("http://localhost:9000/queries")
.then(response => {
const data = response.data;
this.setState({queries:data});
})
}
I'm bit confused, on how to use convertFromRaw to convert the content to the desired text.
Where should I call the method ?
Thanks in advance
You have to understand that DraftJS is a library that converts whatever you have inside the editor into it own format.
For Example, apple is converted to,
{
"blocks": [{
"key": "f6b3g",
"text": "apple",
"type": "unstyled",
"depth": 0,
"inlineStyleRanges": [{
"offset": 0,
"length": 5,
"style": "ITALIC"
}],
"entityRanges": [],
"data": {}
}],
"entityMap": {}
}
Yep, it's that big. So, in order to convert it back from this format to apple you need a component which knows how to interpret it. You cannot just use a div tag. In this case, it's the editor component itself!
So you can do the following to display the content in readonly mode.
<Editor readOnly={true}
editorState={EditorState.createWithContent(this.state.editorState.getCurrentContent())}/>
Now, say if you want to send the editor contents to an API so that you can save it in DB and then get the content from the API and display it.
Convert from Editor Format to JSON
const requestBody = JSON.stringify(convertToRaw(this.state.editorState.getCurrentContent()))
Post JSON to your API
fetch(url, {
method: 'POST',
body: requestBody
});
Get JSON from your API
const response = await fetch(url, {
method: 'GET'
});
Convert from JSON to Editor format and display using Editor (You can remove readonly if you want the user to edit the contents)
<Editor readOnly={true}
editorState={EditorState.createWithContent(convertFromRaw(JSON.parse(response))}/>

How to set up admin-on-rest with couchDB?

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.

Resources