I am using Pixi 6.5.8 and react-pixi, i am trying to load sprite sheet from json file. I am using method i found on codepen examples posted on react-pixi documentation(https://codepen.io/inlet/pen/VwLLYme).
Json was generated from TexturePacker, with output specified for PIXI, so i guess this is not a problem, the same sprite sheet worked perfectly when i used it in Pixi v7 and Assets.load method, however i am forced to work with react now).
Thats the code
export default function JetFighter() {
const [frames, setFrames] = React.useState([]);
const app = useApp();
const spritesheet = "./assets/Sprites/ship_2_idle-0.json";
React.useEffect(() => {
app.loader.add(spritesheet).load((_, resource) => {
setFrames(
Object.keys(resource[spritesheet].data.frames).map((frame) =>
PIXI.Texture.from(frame)
)
);
});
}, []);
if (frames.length === 0) {
return null;
}
return (
<Container x={250} y={250}>
<AnimatedSprite
animationSpeed={0.5}
isPlaying={true}
textures={frames}
anchor={0.5}
/>
</Container>
);
}
Error
I've tried to use Assets.load from "#pixi/assets":^6.5.8", but with this method i am getting such error:
Error from Assets.load method
Do you have any idea how to solve this issue?
Related
In my next js app I'm fetching YouTube playlist and assigning them dynamic card. but when I use map the url doesn't work but in plain omg tag it works fine.
the code is as follows.
index.js
function Home({result}) {
return (
<...
<ShowsView result={result}/>
.../>
)
} export default Home;
export async function getStaticProps(){
const MY_PLAYLIST = process.env.YOUTUBE_PLAYLIST_ID;
const API_KEY = process.env.YOUTUBE_API_KEY;
const REQUEST_URL = `https://youtube.googleapis.com/youtube/v3/playlistItems?part=snippet&playlistId=${MY_PLAYLIST}&key=${API_KEY}`;
const response = await fetch(REQUEST_URL);
const result = await response.json();
return{
props:{result: result},
revalidate: 3600,
}
}
In my index file executing result.items[0].snippet.thumbnails.maxres.url will return a url for the image. the issue is when I map it through the url doesn't work.
{result.items.map((res, idx)=>{
//console.log(res.snippet.thumbnails.maxres);
//console.log(res);
//console.log(result);
return (
//<ShowCard result={result.items[idx].snippet.thumbnails.maxres.url} key={idx}/>
<ShowCard result={res.snippet.thumbnails.maxres.url} key={idx}/>
);
})}
using like this it return every data until I get to the thumbnails. res.snippet.thumbnails.default this works. but res.snippet.thumbnails.default.url throws an error.
TypeError: Cannot read properties of undefined (reading 'url')
This error happened while generating the page. Any console logs will be displayed in the terminal window
The log points after default. What is the mistake here?
Perhaps res is also being accessed during init of the app, which is an empty object.
try doing this:
res.snippet.thumbnails.default?.url
so I'm doing a school project where I'm trying to fetch data from my Azure blob-storage and then displaying it on a website which is creating in ReactJS. I've managed to fetch the pictures from my storage and they render fine, but when I try to render the "createdOn prop" nothing is being shown.
I just wanna add that I'm fairly new to javascript so my code might look like garbage.
The BodyPresenter function is the one that connects to my blob storage and then retrieves the data. It works without a problem for the "blobImages" but won't work for the "blobDateTime"
function BodyPresenter() {
const [blobImages, setBlobImages] = useState([]);
const [blobDateTime, setBlobDateTime] = useState([]);
const account = "ktodb";
const containerName = "images";
useEffect(() => {
async function blobStorage() {
const blobServiceClient = new BlobServiceClient(api_client.get_blob_account(account));
const containerClient = blobServiceClient.getContainerClient(containerName);
let blobs = containerClient.listBlobsFlat();
let newArrayForImages = [];
let newArrayforDates = [];
for await (const blob of blobs) {
// console.log(`${blob.name}`); //`Blob ${i++}:
newArrayForImages.push(blob.name);
newArrayforDates.push(blob.properties.createdOn)
}
setBlobImages(newArrayForImages);
setBlobDateTime(newArrayforDates);
}
return blobStorage;
}, [blobImages])
console.log(blobDateTime)
As you can see I console.log() the blobDateTime at the bottom and it gives me the data I want in the console, aka the creation data of all my images:
image of console
Then I try to render the data in a view file and I guess the problem lies here, but I'm sure what the problem is and how to fix it, to remind you I'm a new to javascript. The images are being rendered but not the DateTime
function BodyView( {blobImages, blobDateTime} ) {
console.log(blobDateTime)
return (
<div>
{blobImages.map( (blobImages, blobDateTime) => (
<div>
<div className="images">
<img
key={blobImages.id}
src={api_client.get_image_url(blobImages)}
alt=""
/>
</div>
<div>{blobDateTime}</div>
</div>
))}
</div>
)
}
I am working on a react file-upload component. I got stuck with a rather trivial issue – I want for each file to show icon corresponding to a file extension. Icons are loaded via css as background images (using inline styles). The problem arises when I don't have an icon for given extension and thus want to show a fallback icon.
– I tried to use multiple css background-image declarations like this:
style={{
backgroundImage: `url(./icons/fallback.svg), url(./icons/${item.extension}.svg)`,
}}
or like this:
style={{
backgroundImage: `url(./icons/fallback.svg)`,
backgroundImage: `url(./icons/${item.extension}.svg)`,
}}
But it doesn't work, the fallback icon is not being used (or in one case I am not able to reproduce, both icon are shown, which is also undesired).
I tried to fetch the file to determine if it does exist, but the node server (i use create-react-app) is configured in a way that returns 200 or 304 even if the file isn't actually present.
I tried to use a solution which creates an image and uses onload and onerror events as beeng suggested in this question, which actually works fine – i am currently using slightly modified implementation of image-exists npm module – but I wasn't able to figure out how to refactor this function to simply return a boolean. Using console.log() and callbacks works fine; returning a boolean results in undefined. I suppose it is due to an asynchronous behaviour od Image methods, but I wasn't able to create a workaround – maybe using a Promise API?
My code:
exists = src => {
const checks = {};
return callback => {
if (src in checks) {
return callback(checks[src]);
}
let img = new Image();
img.onload = function() {
checks[src] = true;
callback(true);
};
img.onerror = function() {
checks[src] = false;
callback(false);
};
img.src = src;
};
};
Render method:
render() {
// So far so good, logs as expected, but not such useful
console.log(this.exists('./icons/jpg.svg')(bool => {
if(bool) {
console.log('yes')
} else {
console.log('no');
}
}));
// ...
}
If I try to return a boolean directly, it results in undefined:
render() {
console.log(this.exists('./icons/jpg.svg')(bool => bool));
// ...
}
You are right, the function does not return a boolean because this is the parameter of the callback of your exists function, which is called asynchronously. The solution is to render your icon asynchronously too, something like...
this.exists(img)(bool => {
if (bool) {
render(img)
} else {
render('fallback.svg');
}
}
O.K. I finally promisify the whole thing. I hooked the former exists function (now checkImage) to a promise chain(saw… massacre…) which is triggered by reading files to upload and results in setState and rerender:
The url checking function:
checkImage = (path, fallback) => {
return new Promise(resolve => {
const img = new Image();
img.src = path;
img.onload = () => resolve(path);
img.onerror = () => resolve(fallback);
});
};
Calling with Promise.all():
// items are array of objects which contains file contents, name, extension etc...
checkIcons = items =>
Promise.all(
items.map(item => {
const url = `./icons/${item.extension}.svg`;
return this.checkImage(url, this.state.fallbackIconUrl).then(result => {
return { ...item, icon: result };
});
})
);
Definitely not the slickiest one in town and it would possibly need some caching (or may not – it does seem the browser can handle this by itself), but works fine.
I'm new with ReactJS and today I have encountered a few problems.
I am currently using Redux to store my data and I was able to retrieve all the data from the props.
Ie.
const { recipe, loadingRDetail } = this.props;
console.log(recipe.macros);
recipe macros will show me 5 values in array.
Array Image Console Log
But when I tried to accessed to the array, It will throw me an error "Cannot read property '0' of undefined".
I have tried
console.log(recipe.macros[0])
and
const {macros} = recipe;
macros.map((i) => {
....
}...
I have no luck with both of these
This is the error I get
Red Warning error
Actually, it's just because your macros data is asynchronously loaded so you have to add a test to check if it's loaded.
You can try this:
const {macros} = recipe;
if (macros && macros.length) {
macros.map((i) => {
....
}...
}
Or if you already are in your Render method you can just try this :
const {macros} = recipe;
return (
{
macros && macros.length && /* It will check if macros has elements inside */
macros.map((i) => {
....
}...
}
}
)
This is hard to phrase into words but I want to get the returned value of a function that is stored in an object, add that value to an array and output it. I have made this all work but it doesn't change once ran again, so say it outputs the random number of 678 it will also output that same number next time and so on. I created this cool terminal in react that gets the command of the key if it exists and outputs it in my console by returning jsx.
Here is my file structure...
Here is my react code... ( I had issues formatting, here is a better version of the code below)
import React, { Component } from "react";
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom';
import "./Main.css";
import Commands from "../Commands/Commands.js"
class Main extends Component {
constructor(props){
super(props);
this.state = {inputValue: ''}
this.outputs = ["type 'help' for information about plunketTheTerminal"];
this.commands = Commands;
this.commands.keys = Object.keys(this.commands)
}
handleSubmit = (event) => {
if(event.key == "Enter") {
if( this.state.inputValue != "" ) {
if( this.commands.keys.includes(this.state.inputValue)) {
this.outputs.unshift(this.commands[this.state.inputValue]);
}
else{
this.outputs.unshift(`No command '${this.state.inputValue}' found.`)
}
}
document.querySelector(".input-section").value = "";
}
this.forceUpdate()
}
handleChange = (e) => {
this.setState({ inputValue: e.target.value })
}
render() {
return(
<div>
<div className="terminal-header"></div>
<div className="terminal-body">
<div className="terminal-contents-wrapper">
<div className="output-item-wrapper">
{
this.outputs.map((output, index) => {
return <h1 className="output-item" key={ index }>{output}</h1>;
})
}
</div>
<div className="input-section-wrapper">
<input type="text" className="input-section" onKeyPress={this.handleSubmit} onChange={this.handleChange}/>
<span className="input-section-label">plunketTheTerminal#plunketTheTerminal-H170-D3H:~$</span>
</div>
</div>
</div>
</div>
)
}
};
export default Main;
Finally my JavaScript file for the commands... ( again better code here )
const rand = () => {
return Math.floor(Math.random() * 1000 ) + 1;
}
const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can actually SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: rand(),
"rand --info": "Will generate a random number between 1 and 1000",
}
export default Commands
EDIT: Trying to use either of the following returns nothing.
rand: () => (
"x"
),
or
rand: () => {
return "x"
},
Here is a demonstration of what is happening...
I type the command...
I get my output which is fine...
but from then on repeating that same command won't generate a new random number i will continue to repeat the first returned value.
I would really appreciate some help but please keep in mind I am still learning react and JavaScript and would love to hear any constructive feedback. I will also continue to update information if needed. Thanks!
Found out what was wrong, I was calling the function without its parentheses. I had to change the command file to the following...
const Commands = {
help: "plunketTheTerminal is a online terminal for fun, it contains lots of different functions and commands. In fact you can SUBMIT YOUR OWN COMMANDS at our github if you are good with computers :).",
rand: () => {
return Math.floor(Math.random() * 1000 ) + 1;
},
//"rand --info": "Will generate a random number between 1 and 1000",
}
and I had to change the line
this.outputs.unshift(this.commands[this.state.inputValue]);
to
this.outputs.unshift(this.commands[this.state.inputValue]());
silly mistake, hopefully this helps someone who has a somewhat similar problem, though I think it would be unlikely.