I am trying to put fetched data into the state but it's not working, please let me know what I am doing wrong here, and also I want specific data to be inside the state like in this example I want only questions, answers, and incorrect answer, also I wanted to put the whole data into the array of object
const [quiz,setQuiz]=useState({});
useEffect(()=>{
const getQuizData =async ()=>{
const res = await fetch("https://opentdb.com/api.php?amount=10")
const data = await res.json();
setQuiz({data});
}
getQuizData();
},[])
what coming from your data is below. I suspect what you want is setQuiz(data.results) also initializing like useState([]) should help too.
const data = {
response_code: 0,
results: [
{
category: 'History',
type: 'multiple',
difficulty: 'medium',
question: 'Joseph Smith was the founder of what religion?',
correct_answer: 'Mormonism',
incorrect_answers: ['Buddhism', 'Christianity', 'Hinduism'],
},
{
category: 'Sports',
type: 'multiple',
difficulty: 'medium',
question: 'In a game of snooker, what colour ball is worth 3 points?',
correct_answer: 'Green',
incorrect_answers: ['Yellow', 'Brown', 'Blue'],
},
],
};
Related
I'm building a post request which will contain various info on each role. E.g in this trial, 'Data Analyst'.
In this position I want to have quite a few sources of data, including things like salary, education and skills.
However, I'm using recharts to visualise it, which means although I need a key, e.g Masters's degree, I also need a num value associated, such as below:
const educationData = [
{
degree: 'Masters',
A: 120,
},
{
degree: 'Bachelor',
A: 98,
},
{
degree: 'PhD',
A: 86,
},
{
degree: 'Industry',
A: 99,
},
{
degree: 'Associate',
A: 85,
}
];
I would like to store this inside my schema created:
const RolesPositionSchema = new mongoose.Schema(
{
title:{type:String, required: true, unique: true},
desc:{type:String, required: true},
skills:{type:Array, required: true},
salary:{type:Array},
education: {type: Array},
popularity: {type: Number},
reccomendations: {type: Array},
},
);
Within this I would like to store the 'educationData' into the DB. Happy to input it in manually for now. I just want to know how to structure my schema/data in the postman request.
E.g Input in "education", stored with "Masters:120", "Bachelor:98", "PhD:86" etc -> within the post request:
{
"title" : "Data Analyst",
"desc": "Using both internal and external data sources you will develop insights to identify trends and opportunities whilst highlighting areas or improvement to optimise member interaction. This is a proactive role where you will own how we interpret data, allowing you to provide valuable insight into the development and implementation of product, customer and channel strategies for our sales, retention, and acquisition goals.",
"skills":["SQL" ,"Excel", "Tableau", "PowerBI", "Python", "Azure", "AWS", "ETL"],
"education": ["INPUT AN ARRAY OF EDUCATION AND THEIR VALUES HERE!]
}
Thankyou!
You could modify first your payload into the format of schema.
Payload
const educationData = [
{
degree: 'Masters',
A: 120,
},
{
degree: 'Bachelor',
A: 98,
},
{
degree: 'PhD',
A: 86,
},
{
degree: 'Industry',
A: 99,
},
{
degree: 'Associate',
A: 85,
}
];
Process
const newEducations = educationData.map(education => {
return `${education.degree}:${education.A}`;
});
const storeRole = new RolesPositionSchema({
title: 'Data Analyst',
desc: 'Using both internal and external data sources you will develop insights to identify trends and opportunities whilst highlighting areas or improvement to optimise member interaction. This is a proactive role where you will own how we interpret data, allowing you to provide valuable insight into the development and implementation of product, customer and channel strategies for our sales, retention, and acquisition goals.',
skills: [{Skill value}],
salary: [{Salary value}],
education: newEducations,
popularity: 0,
reccomendations: [{Recommendation value}]
});
After this saved.
Does it that you want?
So I'm adding a feature to my discord bot to collect the users most recent gameclip, at the moment I'm able to collect all the information in my console log but struggling to understand how to send it in a message. I'm pretty new to this stuff.
This is a snippet of my code right now:
const userXuid = await XboxLiveAPI.getPlayerXUID(gamertag, authInfo).catch(err => message.reply('That gamertag could not be found. Make sure spaces are replaced with \'_\''));
const scores = await XboxLiveAPI.getPlayerScreenshotsFromMediaHub(userXuid, authInfo, num);
console.log(scores);
And this is what gets returned to the console:
{
continuationToken: 'YWJjZGVfdnd4eXoxMDA1',
values: [
{
captureDate: '2016-09-13T19:11:11Z',
contentId: 'e61118b6-c940-4hc9-a32a-49dd53ab4192',
contentLocators: [Array],
CreationType: 'Edited',
localId: '501bf44b-c1b2-4519-b78e-a1f88097f8d1',
ownerXuid: 25332749247888726,
resolutionHeight: 720,
resolutionWidth: 1280,
sandboxId: 'RETAIL',
sharedTo: [],
titleId: 1129121809,
titleName: 'OF: Dragon Rising',
dateUploaded: '2016-09-13T19:12:34.6226406Z',
uploadLanguage: 'en-GB',
uploadRegion: 'GB',
uploadTitleId: 201477059,
uploadDeviceType: 'XboxOne',
commentCount: 0,
likeCount: 0,
shareCount: 0,
viewCount: 2,
contentState: 'Published',
enforcementState: 'None',
safetyThreshold: 'None',
sessions: [],
tournaments: []
}
]
}
Conclusion
So how would I, for example, get captureDate to send in:
message.channel.send(???)
Any help would be appreciated, cheers!
If you're simply talking about accessing captureDate, you'll use scores.values[0].captureDate.
UPDATED CODE
<template>
<swiper-slide v-for="(photon,key) in $store.state.photons" :key='key'>
<radial-gauge :value='photon.tempF'
:options="photon.GaugeOptions.optionsLastTempF"></radial-gauge>
</swiper-slide>
</template>
store.js
export const store = new Vuex.Store({
state: {
photons: {},
token: '',
},
mutations: {
setUser(state, value) {
value.data.forEach(element => {
state.photons[element.id].user = element.data
state.photons[element.id].GaugeOptions.optionsLastTempF.highlights[0].to=parseInt(element.data.tempAlert,10)
state.photons[element.id].GaugeOptions.optionsLastTempF.highlights[1].from=parseInt(element.data.tempAlert,10)+1
});
}},
actions: {
async getData(context) {
let db = []
let photon = {}
db = await axios.get('http://13.14.13.1:3300/DB')
db.data.forEach(item => {
if ([Object.keys(item)[0]] in photon) {
let dataString = (Object.values(item)[0]).split(',')
photon[Object.keys(item)[0]].GaugeOptions={}
photon[Object.keys(item)[0]].GaugeOptions.optionsLastTempF={
title: 'Last Temp',
units: "°F",
minorTicks: 10,
majorTicks: ['0', '20', '40', '60', '80', '100', '120', '140', '160'],
maxValue: 160,
highlights: [{
"from": 0,
"to": 0,
"color": "rgba(0,255,0)"
},
{
"from":0,
"to": 160,
"color": "rgba(255,0,0)"
},
],
colorPlate: '#222',
colorUnits: '#ccc',
colorTitle: '#eee',
colorNumbers: '#eee',
width: 200,
height: 200
}
context.commit('setData', photon)
}
}
}
This code currently works if I go from the homepage to my chart page where this gauges are, but if i refresh the page the gauges have the right values but they aren't being properly update.
UPDATE
so after adding a v-if to my component it now loads properly with everything. I'm now having trouble with how I would call an update function on the gauge?If i'm doing the mutation in my vuex store how would i reference my component to call an update?
So, typically, Vuejs does not watch nested objects. I'd recommend that you rework you code a bit to avoid this. This should help: Vue.js - How to properly watch for nested data
Additionally, it looks like you are trying to reference the Vuex Store object, but you are using the data method rather than the computed method, so you won't get updates on that.
Our GraphQL server responds to a query with data that includes an array of objects each of which shares the same id and different values for a different key. For instance, we might have an array that looks like:
[
{ id: 123, name: 'foo', type: 'bar', cost: 5 },
{ id: 123, name: 'foo', type: 'bar', cost: 6 },
{ id: 123, name: 'foo', type: 'bar', cost: 7 },
{ id: 123, name: 'foo', type: 'bar', cost: 8 }
]
We can see in the Network tab that the response from the server has the correct data in it. However, by the time it goes through processing by the Apollo Client module the array has been transformed into something that might look like this:
[
{ id: 123, name: 'foo', type: 'bar', cost: 5 },
{ id: 123, name: 'foo', type: 'bar', cost: 5 },
{ id: 123, name: 'foo', type: 'bar', cost: 5 },
{ id: 123, name: 'foo', type: 'bar', cost: 5 }
]
Essentially what we're seeing is that if all of the objects in an array share the same value for id then all objects in the array become copies of the first object in the array.
Is this the intended behavior of Apollo Client? We thought maybe it had something to do with incorrect caching, but we were also wondering if maybe Apollo Client assumed that subsequent array members with the same id were the same object.
It looks like this is behavior as intended. The Apollo Client normalizes on id.
As the other answer suggests this happens because Apollo normalises by ID. There's a very extensive article on the official blog that explains the rationale of it, along with the underlying mechanisms.
In short, as seen by Apollo's cache, your array of objects contains 4 instances of the same Object (id 123). Same ID, same object.
This is a fair assumption on Apollo's side, but not so much in your case.
You have to explicitly tell Apollo that these are indeed 4 different items that should be treated differently.
In the past we used dataIdFromObject, and you can see an example here.
Today, you would use typePolicies and keyfields:
const cache = new InMemoryCache({
typePolicies: {
YourItem: {
// Combine the fields that make your item unique
keyFields: ['id', 'cost'],
}
},
});
Docs
It works for me:
const cache: InMemoryCache = new InMemoryCache({ dataIdFromObject: o => false )};
previous answer solves this problem too!
Also you can change the key name(for example id => itemId) on back-end side and there won't be any issue!
I have the same issue. My solution is to set fetchPolicy: "no-cache" just for this single API so you don't have to change the InMemoryCache.
Note that setting fetchPolicy to network-only is insufficient because it still uses the cache.
fetchPolicy document
I'm trying to figure out the best way for my Redux Store to handle lists. Right now it looks like this:
Store = {
users: [],
posts: [],
lists: [],
}
My problem with this, is the list array. Essentially it's a store for paginated lists of a specific resource, so for example:
lists: [
{
id: 'users/43/posts',
items: [25, 36, 21]
}
]
Since I am using the url as the id, my component that shows a user's list of posts will know exactly which list to display. Now someone has told me that, this is a very very bad idea. And I just want some advice on what could be better. Another approach suggested was this:
users: [{
id: 2,
posts: [
{
url: 'users/2/posts',
items: [13, 52, 26],
}
]
}]
So what I don't understand, how does Redux know where to save this list? Do I have to specify in the action arguments where to save it?
Thank you for your advice.
Well, technically, anything works if you make it work! The second approach looks more mature, though. You don't want to use URLs as ID. IDs should be numbers or special sequence of characters+numbers. When your application grows, you'll want to normalize your data i.e. store the IDs in a separate array and transform the array of objects into an object with keys as ID.
Example from Normalizr
[{
id: 1,
title: 'Some Article',
author: {
id: 1,
name: 'Dan'
}
}, {
id: 2,
title: 'Other Article',
author: {
id: 1,
name: 'Dan'
}
}]
can be normalized to -
{
result: [1, 2],
entities: {
articles: {
1: {
id: 1,
title: 'Some Article',
author: 1
},
2: {
id: 2,
title: 'Other Article',
author: 1
}
}
}
}
When your application grows, you'll have multiple reducers and sub-reducers. You'll want to slice a specific portion of your state-tree and so on. For that reason someone might have advised you to store your state in a different manner.
But again, anything works if you make it work! Good luck!