I am trying to display on a single page react app, the icons from items, but as a response from the fetch, instead of getting an array of objects, I'm getting only one object, which doesnt have the data from my db.json.
My question is: How can I reach the "displayIcon" if I can't get a correct response?
Here is my function, and below the db.json:
const [weapons, setWeapons] = useState(null);
useEffect(() => {
console.log('effect triggered');
fetch('http://localhost:3001/data/', {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
}
})
.then((res) => res.json())
.then((data) => setWeapons(data));
}, []);
console.log('render', weapons)
"data": [
{
"uuid": "1",
"displayName": "Odin",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "f454efd1-49cb-372f-7096-d394df615308",
"displayIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/HMG/HMGPrimaryAsset",
},
{
"uuid": "2",
"displayName": "Ares",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "5305d9c4-4f46-fbf4-9e9a-dea772c263b5",
"displayIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/LMG/LMGPrimaryAsset",
}
If you are trying to render a single image, you can get the item by uuid and render the image (or anything else).
Here's an example component That accesses the weapon with uuid of 2. In your app you'd probably want to pass uuid to this component using props, but the same logic will apply.strong text
// get weapon by uuid
const ShowIcon = () => {
let weapons = {
"data": [
{
"uuid": "1",
"displayName": "Odin",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "f454efd1-49cb-372f-7096-d394df615308",
"displayIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/63e6c2b6-4a8e-869c-3d4c-e38355226584/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/HMG/HMGPrimaryAsset",
},
{
"uuid": "2",
"displayName": "Ares",
"category": "EEquippableCategory::Heavy",
"defaultSkinUuid": "5305d9c4-4f46-fbf4-9e9a-dea772c263b5",
"displayIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/displayicon.png",
"killStreamIcon": "https://media.valorant-api.com/weapons/55d8a0f4-4274-ca67-fe2c-06ab45efdf58/killstreamicon.png",
"assetPath": "ShooterGame/Content/Equippables/Guns/HvyMachineGuns/LMG/LMGPrimaryAsset",
}
]
}
let weapon = weapons.data.filter(i => i.uuid == 2 ? 1 : 0);
return(
<div>
<img src={weapon[0].displayIcon} />
</div>
);
}
ReactDOM.render(<ShowIcon />, document.getElementById('icon'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="icon"></div>
Related
I have JS object in the following format which i want to send at backend. I have implemented some code but at nodeJs controller it says hotel is undefined. My written code is following:
let hotel = new FormData();
hotel.append('name', data.append);
hotel.append('slug', data.slug);
hotel.append('logo', data.logo);
hotel.append('coverAvatar', data.coverAvatar);
hotel.append('designs', [{ name: `${+new Date()}`, url: localStorage.getItem('initialDesign') }])
hotel.append('products', [...selectedVariants]);
axios.post(`${baseURL}/hotel`, { hotel },{
headers: {
'Authorization': localStorage.getItem('_AUTH_TOKEN'),
'Content-Type': 'multipart/form-data'
}})
.then(response => {
console.log({ response });
})
.catch(err => {
console.log('err', err);
})
I'm using multipart/form-data because logo and coverAvatar are output of <input type='file' />
My data Format
{
"name": "preshan hotel 2",
"logo": {file},
"coverAvatar": {file},
"romms": [{
"name": "tempDesign",
"url": "https://picsum.photos/600/800"
}],
"facilities": [
{ "facilityId": "61ceb3931b1b68fe90827f23", "facilityMappings": ["61ceb39b1b1b68fe90827f2c", "61ceb39b1b1b68fe90827f41"] },
{ "facilityId": "61ceb3ca1b1b68fe90827f47", "facilityMappings": ["61ceb3ca1b1b68fe90827f50","61ceb3ca1b1b68fe90827f58", "61ceb3ca1b1b68fe90827f56"] },
{ "facilityId": "61ceb3e41b1b68fe90827f5d", "facilityMappings": ["61ceb3e41b1b68fe90827f5f"]}
]
}
You should pass your formdata directly instead of passing an object.
In your example it would look like this:
...
axios.post(`${baseURL}/hotel`, hotel,{
...
Api Respose :-
[
{
"System Name": "Name1",
"Primary Sensor": "WWWW",
"Mean Wind Speed": "6.23 m/s",
"Status": 1,
"mws_number": 44,
"DRR (%)": "100",
"drr_number": 100
},
{
"System Name": "Name 2",
"Primary Sensor": "SSSS",
"Mean Wind Speed": "4.2 m/s",
"Status": 2,
"mws_number": 6,
"DRR (%)": "100",
"drr_number": 100
}
]
My Code ->
class Home extends Component {
state = {
items:[],
isLoading:false
}
componentDidMount() {
// api
fetch('http://api.url', {
method: 'POST',
body:
JSON.stringify({"Authentication":'token'})
}).then(data => data.json() )
.then(res =>{
this.setState({isLoading:true,
items:res,}
)
});
}
render() {
return (
<>
{console.log(this.state.items[0])} // getting o/p - first obj of array
{console.log(this.state.items[0].Status)} // getting Error undef Status
{console.log(this.state.items.Status[0])} // same error undef status
</>
)
export def ....
This is my complete piece of code... I can't add api url as it is not public api :(
I want to access this data inside of the array =>(Status, System Name, etc)
how can i fetch this !!
Here, console.log(this.state.items[0]); is getting called two times;
- When the page first loads and API request is not finished.
- After the API request finishes and you call this.setState
Solution would be to check that items' length is greater than 0 before trying to use it. Try changing console.log(this.state.items[0]); to this:
if (this.state.items.length > 0) { console.log(this.state.items[0].Status); }
I would suggest you to use componentWillMount() instead of componentDidMount() becuase componentWillMount() happens before render while componentDidMount() happens after the first render.May be that help.
I'm very new to React. I have a JSON response that is being returned to me VIA WebAPI 2.
I would like to display only parts of this reply, for example if i only want to display the title
I have implemented the following code, but when view title it shows up as undefined
App.js
class App extends React.Component {
constructor(props){
super(props);
this.state = {reply: ""}
this.callAPI = this.callAPI.bind(this);
}
componentDidMount(){
this.callAPI();
}
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json();
}).then(responseData => {
this.setState({reply:responseData});
console.log("REPONSEDATA-----"+responseData);
console.log(responseData.title);
});
}
render(){
return(
<div>
</div>
);
}
}
Update 1
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(response =>{
return response.json().then(responseData => {
this.setState({reply:responseData});
console.log("RESPONSE----"+JSON.stringify(responseData));
console.log(responseData.title);
});
});
}
API JSON Response
[{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 1,
"externalId": null
},
"internalVersion": 2,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._Annual Returns_2012-01-03",
"extension": "pdf",
"logicalSize": "47872",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:41.510Z",
"lastAccessedAtUtc": "2019-07-10T21:00:28.029Z",
"lastWrittenAtUtc": "2019-05-27T15:17:48.000Z",
"changedAtUtc": "2019-05-27T15:17:48.000Z",
"fileGuid": "{881D8975-84B9-4A73-9AFF-F0C61C94FE90}",
"checksumMD5": "24f6badff8b70783697e0052fc4a7fe6",
"fileMissing": false,
"contentIsVolatile": false
}][{
"fileVer": {
"type": "specific",
"fileId": {
"type": "specific",
"internalId": 2,
"externalId": null
},
"internalVersion": 3,
"externalVersion": null,
"versionSortKey": "0"
},
"title": "1576544 Alberta Ltd._By-Law #1_",
"extension": "pdf",
"logicalSize": "951046",
"sizePrecision": "exact",
"createdAtUtc": "2019-05-27T15:22:42.000Z",
"lastAccessedAtUtc": "2019-07-10T21:02:54.062Z",
"lastWrittenAtUtc": "2019-05-27T15:16:28.000Z",
"changedAtUtc": "2019-05-27T15:16:28.000Z",
"fileGuid": "{F8B54DB0-7E9F-4F0F-8ABA-D03C1DE4FF8C}",
"checksumMD5": "ffe728ef1a87f0cec7737b6d224bb50d",
"fileMissing": false,
"contentIsVolatile": false
}]
Not sure what im doing wrong here, ive used Ajax a lot so maybe im confusing what can be done with react and fetch
Update 2
So it seems that this may be a single object, and not an array of objects.
console.log("RESPONSE----"+JSON.stringify(responseData));
var arr = [];
console.log("KEYS"+Object.keys(responseData));
Object.keys(responseData).forEach(function(key){
console.log(responseData[key]);
arr.push(responseData[key]);
When i try to access responseData[key] i end up getting a single letter, and not a property from the json response
This pushes me to believe that this is not an array of objects but a single object
you should use JSON.stringify when printing full json response and if part of the object is string (eg... response.title then its ok but if not you can try .toString() or JSON.stringify)
callAPI(){
fetch('http://localhost:51092/api/COM',{
method:'get',
headers:{'Content-Type':'application/json'}
}).then(function(response){
return response.json().then((responseData)=>{
this.setState({reply:responseData});
console.log("REPONSEDATA----"+JSON.stringify(responseData));
console.log(responseData.title);
return responseData
});
}
I have an API response that contains an item hash. I want to be able to cross reference that item hash with a lookup table that is stored locally in my project, so I am able to display a name and icon path of the item that matches the hash.
I have tried storing the item hash in state and tried to reference it in my render function like so const weaponURL = hashdata[{weapon}.displayProperties.icon];. I'm getting an error saying the Cannot read property 'icon' of undefined.
I have also tried to reference the icon path using this code in render {baseURL + {weapon && hashdata[weapon].displayProperties.icon}} but I get an error from my IDE to say that : is expected
Here is my entire JS file:
import React, {Component} from 'react';
import hashdata from '../data/data';
import ReactTooltip from 'react-tooltip';
import apiKey from '../data/apiKey';
class XUR extends Component {
state = {
isLoading: false,
error: null,
xurInventory: null,
weapon: null,
gear1: null,
gear2: null,
gear3: null
};
async componentDidMount() {
this.setState({
isLoading: true
});
try {
const xurFetch = await fetch('https://www.bungie.net/Platform/Destiny2/Vendors/?components=402', {
headers: {
'X-API-KEY': apiKey
}
});
if (!xurFetch.ok) {
throw Error(xurFetch.statusText);
}
const xurInvJson = await xurFetch.json();
this.setState({
xurInventory: xurInvJson,
weapon: xurInvJson.Response.sales.items.data[2190858386].saleItems[54].itemHash,
isLoading: false
});
} catch (error) {
this.setState({error: true});
}
}
render() {
const {isLoading, error, weapon} = this.state;
const baseURL = 'https://www.bungie.net';
const weaponURL = hashdata[{weapon}.displayProperties.icon];
if (isLoading) {
return (
<div>
<p>LOADING</p>
</div>
)
}
if (error) {
return(
<div>
<p>Error</p>
</div>
)
}
return (
<div>
<div className={"row justify-content-center"}>
<div className={"col-6 text-center py-2"}>
<img alt="icon" src={baseURL + {weapon && hashdata[weapon].displayProperties.icon}}/>
<ReactTooltip/>
</div>
</div>
</div>
)
}
}
export default XUR;
Here is a snippet from my data hash file:
const hashdata = {
"31953744": {
"displayProperties": {
"description": "",
"name": "Holy Ground",
"icon": "/common/destiny2_content/icons/d76ab9a89d00451c6a0c1d779a3e5f98.jpg",
"hasIcon": true
},
"scope": 1,
"sourceString": "Source: Complete activities and earn rank-up packages on Io.",
"sourceHash": 315474873,
"itemHash": 31953744,
"acquisitionInfo": {
"runOnlyAcquisitionRewardSite": false
},
"stateInfo": {
"requirements": {
"entitlementUnavailableMessage": ""
},
},
"presentationInfo": {
"presentationNodeType": 1,
"parentPresentationNodeHashes": [
631010939
],
"displayStyle": 3
},
"hash": 259147463,
"index": 2171,
"redacted": false,
"blacklisted": false
},
"31953747": {
"displayProperties": {
"description": "",
"name": "Ballet Lover",
"icon": "/common/destiny2_content/icons/c89eb559068c19f8ed62d56a47f33cfa.jpg",
"hasIcon": true
},
"scope": 1,
"sourceString": "Source: Complete activities and earn rank-up packages on Io.",
"sourceHash": 315474873,
"itemHash": 31953747,
"acquisitionInfo": {
"runOnlyAcquisitionRewardSite": false
},
"stateInfo": {
"requirements": {
"entitlementUnavailableMessage": ""
},
},
"presentationInfo": {
"presentationNodeType": 1,
"parentPresentationNodeHashes": [
631010939
],
"displayStyle": 3
},
"hash": 259147462,
"index": 2170,
"redacted": false,
"blacklisted": false
},
"32806262": {
"displayProperties": {
"description": "\"Our mysterious defender slew a Kell today. Kandak has banned other Risen and put a bounty on the so-called Red Moon Phantom's head.\" —Annals of the Saharan Contested Zone",
"name": "Cloak of Five Full Moons",
"icon": "/common/destiny2_content/icons/8e0e7dfa87d5c68262b6027cd22efd40.jpg",
"hasIcon": true
},
"scope": 1,
"sourceString": "Source: Open Legendary engrams and earn faction rank-up packages.",
"sourceHash": 3334812276,
"itemHash": 32806262,
"acquisitionInfo": {
"runOnlyAcquisitionRewardSite": false
},
"stateInfo": {
"requirements": {
"entitlementUnavailableMessage": "Requires Destiny 2: Forsaken"
},
},
"presentationInfo": {
"presentationNodeType": 2,
"parentPresentationNodeHashes": [
3988275539
],
"displayStyle": 3
},
"hash": 39866533,
"index": 510,
"redacted": false,
"blacklisted": false
}
}
Is anyone able to tell me where I'm going wrong? Is it possible to reference the hash table this way or will I have to store the state hash value in a variable and then reference that variable when making my call to the hash table?
I am using ReactJS.
EDIT:
I'm trying to call the icon path and place it behind a base URL in the renders img tag, so I can show the icon of specific items. I have managed to get this working using localStorage and storing the value of the hash but I was wondering if it's possible without using localStorage as the code was incredibly messy and it seemed like a long winded way of doing things, especially when I was having to create localStorage items for many items at a time.
First of all, I'm working with the Unofficial Xbox API and I'm trying to display the images from the endpoint example CLICK HERE that is provided inn the website.
So I'm using a button with callback to a Fetch API function:
document.getElementById('getScreenshots').addEventListener('click', getScreenshots);
function getScreenshots(){
// Get data from URL
fetch('https://xboxapi.com/v2/screenshots/1144039928',{
headers: new Headers({
"X-Auth": "HERE-GOES-MY-API-KEY",
"Content-Type": "application/json",
})
})
.then((res) => res.json())
.then((data) => {
let output = '<h5>List of Recent Screenshots</h5>';
data.forEach(function(screenshot){
output += `
<ul>
<li>ID: ${screenshot.screenshotId}</li>
<li>Published at: ${screenshot.datePublished}</li>
<li><img src="${screenshot.uri}"></li>
</ul>
`;
});
document.getElementById('screenshots').innerHTML = output;
})
.catch((err) => console.log(err))
}
<button id="getScreenshots">Get Screenshots</button>
<ul id="screenshots"></ul>
but everytime that I try to request it, the images are not shown and the console trows me an error of 404 for each image. Here is what I'm talking about:
Can anybody help me with this?.
Thanks in advance.
UPDATE, this is the json data that I get when using Postman:
"thumbnails": [
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Small"
},
{
"uri": "https://screenshotscontent-t5002.xboxlive.com/xuid-2535443387655711-public/29cd392a-6758-4926-8396-44aa77822ac6_Thumbnail.PNG",
"fileSize": 0,
"thumbnailType": "Large"
}
],
"screenshotUris": [
{
"uri": "https://screenshotscontent-d5002.xboxlive.com/xuid-2535443387655711-private/29cd392a-6758-4926-8396-44aa77822ac6.PNG?sv=2015-12-11&sr=b&si=DefaultAccess&sig=5Is2Shl9m0c85yI0Vq%2BTRs3cuwYDvUR2BBWrD2%2FpkIw%3D",
"fileSize": 1255362,
"uriType": "Download",
"expiration": "2018-08-29 04:51:56"
}
],
"xuid": 2535443387655711,
"screenshotName": "",
"titleName": "Halo: The Master Chief Collection",
"screenshotLocale": "en-US",
"screenshotContentAttributes": "None",
"deviceType": "Durango",
"screenshotDetails": "https://xboxapi.com/v2/2535443387655711/screenshot-details/d1adc8aa-0a31-4407-90f2-7e9b54b0347c/29cd392a-6758-4926-8396-44aa77822ac6"
},
screenshot.screenshotUris.uri will be undefined because screenshot.screenshotUris is an array. So you need:
screenshot.screenshotUris[0].uri
or making a cycle like
screenshot.screenshotUris.forEach(function(el) { ...el.uri... })