I am trying to make a game where you first need to make a deck with. The problem is that when people add cards that dont exist, it wont say that the card doesnt exist. I tried to fix this, but everything I tried doesnt work. I am on discord.js v12. my code is:
const cards = [
`Miner`,
`Fighter`,
`Skipper`,
`Finder`,
`Bomber`,
`Master of an Element`,
`Master of all the Elements`,
]
client.on("message", message => {
if (message.content.startsWith("card1")) {
let deckSlot1 = message.content;
deckSlot1 = deckSlot1.substring("card1".length, deckSlot1.length);
if (!deckSlot1) return message.channel.send("You didnt include a card!")
console.log(deckSlot1)
if(deckslot = cards) {
message.channel.send(`Your first card is${deckSlot1}`)
console.log("In there")
} else if(deckslot != cards) {
message.channel.send("That card doesn't exist?")
console.log("Not in there")
}
}
})
Please take a look at <Array>.includes method, you are trying to check equality (don't forget to use double equal when you want to verify an equality else it's an assignation) between an array and a string, instead you could check if the array has the string.
Exemple for your case:
if(cards.includes(deckSlot1)) {
// It's a card
else {
// It's not a card
}
Related
I'm trying to get the temperature of each hour from this website: https://www.smhi.se/vader/prognoser/ortsprognoser/q/Stockholm/2673730
I'm getting the data from https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16/lat/58/data.json. The "t" object is the temperature.
The problem I have is displaying the data for each hour in the repeater.
Here is my backend-code:
import { getJSON } from 'wix-fetch';
export async function getWeather() {
try {
const response = await getJSON('https://opendata-download-metfcst.smhi.se/api/category/pmp3g/version/2/geotype/point/lon/16/lat/58/data.json');
console.log(response) // all data
const tempData = response.timeSeries[0].parameters[10].values[0];
return tempData // Only returns "t" - temperature
} catch (e) {
return e;
}
}
The backend part works, however the frontend doesn't.
import { getWeather } from 'backend/getSMHI.jsw'
$w.onReady(function () {
(
getWeather().then(weatherInfo => {
$w('#weatherRepeater').onItemReady(($item, itemData, index) => {
if (index > 6) {
$item('#tempText').text = itemData.timeSeries[index].parameters[1].values[0];
} else if (index === 6) {
$item('#tempText').text = itemData.timeSeries[index].parameters[0].values[0];
} else {
$item('#tempText').text = itemData.timeSeries[index].parameters[10].values[0];
} // The parameters number for "t" changes depending on the index
})
$w('#weatherRepeater').data = weatherInfo;
})
)
})
Seems like there are at least a couple of issues here.
First, you are retrieving a single number from the API and trying to put that in a repeater. From the description of what you're trying to do, it would seem that you mean to be retrieving a list of numbers, probably as an array. You probably want to do some filtering and/or mapping on the response data instead of directly accessing a single value.
Second, the data you send to a repeater must be in the proper format. Namely, it must be an array of objects, where each object has a unique _id property value (as a string). You are not doing that here. You are simply assigning it a number.
Third, and this is just an efficiency thing, you don't need to define the onItemReady inside the then(). Not that it will really make much of a difference here.
I am doing an axios.get call on an API, in React. When I run it the first time, I get the results that I expect. When I run it the next time and search for the same thing, I get more results than I had originally. Then if I search again, for the same thing, I get even more results that I had the second time. It keeps adding new results to the old ones without starting a brand new search. If I search for a different keyword, then I get results with both the new keyword results and the old ones that I did before.
There is probably an easy fix to this, but how do I get it to discard the old results and create new ones? I have tried creating CancelTokens, but haven't been successful.
I am currently putting the results into a new array and I set that array equal to nothing when I first render the component, so I don't understand how this problem is happening in the first place.
Thanks for any help you can offer!
async componentDidMount() {
//searches the api for the hashtag that the user entered
newArray.length=0;
newArray=[];
await axios.get(`https://laffy.herokuapp.com/search/${this.props.toSearch}`).then(function(response) {
returnedKeywordSearch = response.data;
}) //if the api call returns an error, ignore it
.catch(function(err) {
return null;
});
//goes through the list of locations sent from the api above and finds the latitude/longitude for each
var count = 0;
while (count < returnedKeywordSearch.length) {
locationToSearch = returnedKeywordSearch[count].location;
if (locationToSearch !== undefined) {
var locationList = await axios.get(`https://api.mapbox.com/geocoding/v5/mapbox.places/${locationToSearch}.json?access_token=pk.eyJ1IjoibGF1bmRyeXNuYWlsIiwiYSI6ImNrODlhem95aDAzNGkzZmw5Z2lhcjIxY2UifQ.Aw4J8uxMSY2h4K9qVJp4lg`)
.catch(function(err) {
return null;
});
if (locationList !== null) {
if (Array.isArray(locationList.data.features) && locationList.data.features.length)
{
locationCoordinates.push(locationList.data.features[0].center);
if (returnedKeywordSearch[count].location!== null && returnedKeywordSearch[count].location!==""
&& locationList.data.features[0].center !== undefined)
{newArray.push({
id: returnedKeywordSearch[count].id,
createdAt: returnedKeywordSearch[count].createdAt,
text: returnedKeywordSearch[count].text,
name: returnedKeywordSearch[count].name,
location: returnedKeywordSearch[count].location,
coordinates: locationList.data.features[0].center
});
}
}
}
}
count++;
}
//tweetSpots is set to null in the initial component state set up
this.setState({tweetSpots: newArray});
this.setState({ done: true}); //sets done to true so that loading animation goes away and map displays
}
Okay, I figured out this problem is actually on the server side in Express where the data isn't being reset. So, I'll close this one and open a question about Express.
In essence, I have this working, I am building out a game component to allow users to select items they want to purchase, they get pushed into a pending array and then when they wish to check out I am pushing those objects from the pending array into the purchased array.
But something very odd is happening after that, the arrays look like it worked properly the pending array is empty and the purchased array has the correct items within it. The problem comes once I try and click a new item to put into the pending array if its the same item that is in the purchased array it alters the counter there.
I have been toying with different ways to try and fix this, but have no idea how it's affecting the purchased array without me setting the state again.
This is my code so far for operating this vendor functionality.
handleMerchantEquipment(item) {
let pending = this.state.merchantPending;
let found = Equipment.find(el => item === el.Name);
let check = pending.find(el => el.Name === found.Name);
if (!check) {
pending.push(found);
}
else {
var foundIndex = pending.findIndex(el => el.Name === check.Name);
check.Count +=1;
pending[foundIndex] = check;
}
let CP = [0];
let SP = [0];
let GP = [0];
let PP = [0];
pending.map(item => {
let cost = item.Cost * item.Count;
if (item.Currency === "CP") {
CP.push(cost);
}
else if (item.Currency === "SP") {
SP.push(cost);
}
else if (item.Currency === "GP") {
GP.push(cost);
}
else if (item.Currency === "PP") {
PP.push(cost);
}
});
let purchased = [];
this.state.merchantPending.map(item => {
purchased.push(item)
});
this.setState({
yourCP: totalCP,
yourSP: totalSP,
yourEP: totalEP,
yourGP: totalGP,
yourPP: totalPP,
purchased: purchased,
merchantPending: [],
});
Some of the code is related to the currency exchange which his working fine.
I have also tried the ... to update the array but the issue persisted with it updating the Count in the purchased state.
You are mutating state. You should not mutate state in React. You should always immutably change state in React.
I think the problem lies in this line.
let pending = this.state.merchantPending;
Change it to
let pending = [...this.state.merchantPending.map(obj => ({...obj}))];
Also, if you want to iterate an array, use forEach instead of map. map returns you a new array.
pending.forEach(item => {
...
}
What is that you want the purchasedArray to do when it encounters a duplicate entry or item? May you clarify that in your question?
If you want it to not allow duplicate items you have to first check the array to see if it contains that item. Pseudo code
if(contains) {
render alert
//or do something else
} else {
purchased.push(item)
}
I am not able to comment so I will delete this when you clarify.
For example, if I want to get a list of planets and the orbital length of them I can do this:
query Planets {
planets {
id
name
orbitalLength
}
}
But let's say it takes a long time to calculate the orbital length and it sometimes throws an error, so I don't want to wait for those values with the first render.
#defer would be a great solution for this problem but it isn't implemented yet, but I could load them one by one and display as they arrive, but I'm not sure, how should it be done.
Maybe something similar could work (but compose won't accept a function as a parameter):
const Feeder = graphql(gql`{
planets {
id
name
}
}`)
const Feeder2 = Feeder(compose(props => (props.data.planets || []).map(planet => {
return graphql(gql`{
orbitalLength(idPlanet: $idPlanet)
}`, {
name: `orbitalLength-${planet.id}`,
options: {
variables: {
idPlanet: planet.id
}
}
})
})))
const FeededComponent = Feeder2(Component)
Hello I have array of friends this.venner
also I have array called this.convensations and output is like this.venner,
but id here is called partner_id (partner_id output is 54312, 54345, 54346 )
now I want compare if this.convensation partner_id and this.venner id if is same
something like this:
if (this.convensation in this.venner) {
//do something
} else {
// do something
}
You can use the Array.prototype.some() method.
If you wrap that in it's own checkExistsInArray function...
function checkExistsInArray(arr, compareObj){
return arr.some(function(obj){
return compareObj[Object.keys(compareObj)] === obj[Object.keys(compareObj)];
});
}
... then you should be able to use that for both arrays by passing in a custom compare object.
var friendExists = checkExistsInArray(this.venner, { id: this.friend });
var conversationExists = checkExistsInArray(this.conversations, { partner_id: this.friend });
Side Note : As others have pointed out, there are libraries out there to readily do this sort of thing. Two of the main players I'm aware of are Underscore.js and Lodash. Even if you choose not to use them, it can sometimes be helpful to see how they work under the hood when looking for a little bit of inspiration.
You can use filter,
var result = this.venner.filter(t=>t.id === '54312');
if (result.length >0) {
//do something
} else {
// do something
}
Simply you can solve this using Undescore.js _.find function
if (.find(this.friend, {"id":this.venner) {
//do something
} else {
// do something
}