I'm trying to use useFetch in Nuxt3, however, the responses have a weird format.
Here is the code:
<script setup>
const [{ data: organization }, { data: repos }] = await Promise.all([
useFetch('https://api.github.com/orgs/nuxt'),
useFetch('https://api.github.com/orgs/nuxt/repos'),
])
console.log('--------organization', organization)
console.log('----------repos', repos)
</script>
And here is the response:
The _rawValue and _value actually contain the data I need, however, I think this should just be a simple JSON. I'm not sure why it's returning data this way
Related
I am new javascript. I could do this in 2 seconds in python/java but I am struggling here. I am developing an reactJS app. I am retrieving a string which is a dictionary/HashMap<String, ArrayList> from a server via axios. I get response.data and my data is in the form:
{ "key1": [1,23,4,5,5,2],
"key2": [2,6,5,5,5,6,5],
...
}
I want to convert this into a map/dictionary so I can access it like so (get(), keys(), etc.
However, i am having trouble doing this.
console.log(typeof data) gives me string.
And when I JSON.parse() or JSON.stringify() and use new Map() i get this weird thing with thousands of integer keys and it doesn't act like I want. Any idea on how I can do this?
Thanks!
EDIT
Here is a more complete code example.
const fetchData = () => {
const url = "http://127.0.0.1:8081/pdata";
const promise = axios.get(url);
console.log(promise);
const dataPromise = promise.then((response) => response.data);
console.log(dataPromise);
return dataPromise;
}
export default function Home() {
//Bind the data to a useState Hook in React, to ensure that we have the correct data
const [data, setData] = React.useState([]);
//This function runs on page reload, twice. Your fetch data function will run repeatedly while contained
//within this functional component.
useEffect(() => {
fetchData().then((apiEndpoint) => {
//setting data equal to the result of the FetchData function
setData(apiEndpoint);
}).catch(err => console.log(err))
}, [])
// We now have the data.
// Convert it to a map
const map = new Map(Object.entries(data));
console.log(map.get("Model Used"));
console.log([...map.keys()]);
At point We now have the data, console.log(data) prints the incoming data correctly its just is of type string not map or whatever javascript calls it.
Using Map and Object#entries:
const obj = { "key1": [1,23,4,5,5,2], "key2": [2,6,5,5,5,6,5] };
const map = new Map(Object.entries(obj));
console.log(map.get("key1"));
console.log([...map.keys()]);
From https://flexiple.com/javascript/javascript-dictionary/
Are there dictionaries in JavaScript? No, as of now JavaScript does not include a native “Dictionary” data type. However, Objects in JavaScript are quite flexible and can be used to create key-value pairs. These objects are quite similar to dictionaries and work alike.
It seems you can just parse the string that you obtained to JSON and use the parsed object obtained. For example:
var api_response = `
{
"key1": [1,23,4,5,5,2],
"key2": [2,6,5,5,5,6,5]
}`;
var parsed_data = JSON.parse(api_response);
console.log(Object.keys(parsed_data))
console.log(parsed_data["key2"])
console.log(parsed_data.key1)
I am trying to fetch data in react from mongodb using axios, I receive an array of objects on applying the GET method, but I am unable to store data in a state properly and use the data from the state in desired form, I want to fetch a particular ker's value here i.e. title. Please help me to solve this or suggest a better way of doing this.
[state, setState] = useState()
useEffect( async () =>
{
axios({
"method": "GET",
"url": "http://localhost:5500/api/add/",
"headers": {
"Content-Type": "application/json",
}
})
.then((response) => {
setState(response.data)
})
.catch((error) => {
console.log(error)
})
const title = state[1].title
console.log(title)
}, state)
The data is stored in mongodb as an array of objects having key:value pairs, I received following output when I used input - console.log(response.data[1].title)
output- title-2
for data object:
1: {_id: "5f6e10d3509b062528381884", title: "title-2", details:
"details-2", __v: 0}
After that, when I used console.log(state[1].title) i received
TypeError: Cannot read property 'title' of undefined while trying to
access data from an array of objects
i think you are asking for state[1].title before axios returns the data and save it to the state.
if it that the case its means you state is underfined
I'm trying to post data from Axios to my API but although my json data looks correct when passing to Axios, browser tools tells me that my nested property is empty.
My data contains nested objects and looks like this:
{
'name': 'foo',
'index': 1,
'nested': [
{
'date': '2020-05-10',
'geojson_data': {
'crs': Object,
'name': 'my-name',
'type': 'FeatureCollection',
'features': [{ ... }, { ... }]
}
},
]
}
Edit: geojson_data results from parsing .geojson file, thus, the features array contains ~300 items.
My axios function is defined here:
async post(data) {
console.log(data);
return axios
.post(API_URL + 'endpoint/',
data,
{
headers: authHeader()
})
.then(response => {
return response.data;
})
}
authHeader() is used to provide Bearer token authorization.
I check that data passed to axios is correct (looks like above), but browser tools tell me that data actually sent looks like
{"name":"foo","index":1,"nested":[]}
Why is my array empty ?
Edit: I tried to manually populate a sample nested object and it seems to work. Yet, whenever I use my actual data, it doesn't.
Don't know if it's relevant but in the console, here is the difference I can see between the 2 collapsed objects (actual vs sample):
Sample : Object { name: "foo", index: "1", nested: (1) […] }
Actual : Object { name: "foo", index: "1", nested: [] }
Notice the nested array which looks like it is empty. Yet, if I expand it, they look the same. Any ideas ?
P.S: looks like this SO post from 3 years ago, but without solution
when I do this:
const uuidapi = await axios.get('https://api.hypixel.net/player?key=mykey&name=' + args[1]);
console.log(uuidapi);
I get this response from Axios:
https://paste.menudocs.org/paste/7vppu
So my question is: How do I get the Data after "socialMedia"? Heres how socialMedia looks like:
"socialMedia": {
"links": {
"YOUTUBE": "https://www.youtube.com/channel/UC1L7H9qQyB2zZgt-1XUv6jA",
"DISCORD": "Altpapier#4847"
}
}
Why does it say socialMedia: [Object], and how do I get more than this?
I can't use const { data } = await axios.get(URL); because I want to get 2 URL responses with the complete data.
I also want to be able to safe for example the DISCORD Name Altpapier#4847 how do I do that?
All the data is already here, it's just the formatting of console.log that's not printing every nested object.
If you replace
console.log(uuidapi);
by
console.log(JSON.stringify(uuidapi));
it will work better
See this question: How can I get the full object in Node.js's console.log(), rather than '[Object]'?
you can use console.dir( yourObject, { depth: null } )
I am using axios.all to do asynchronous calls to the YouTube API.
My code is:
export default {
data () {
return {
cats: [],
dogs: [],
catsAndDogs: []
}
},
methods: {
search: function (){
var that = this
axios.all([
axios.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=cats&key=API_KEY'),
axios.get('https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=25&q=dogs&key=API_KEY')
])
.then(axios.spread(function (catsRes, dogsRes) {
that.cats = catsRes
that.dogs = dogsRes
console.log(catsRes)
console.log(dogsRes)
}))
}
}
}
This is as far as I can get because when I try to put the response from axios.spread (catsRes or dogsRes) into the arrays, they end up empty.
However if I comment out 'that.cats = catsRes' and 'that.dogs = dogsRes' the console prints out the response fine.
Can someone tell me why this is not working?
Ideally I would like to have an array for just the cat videos, an array for the dog videos and an array with both cats and dogs.
* EDIT *
Top is the console response when I try to put the GET request data into the data element and bottom is the console response when I don't try to put the GET request data into the data element:
https://imgur.com/a/NY1nc
The axios response is an object with some additional information about the response. To get the actual response JSON data, use the response object's data property. Furthermore, it seems like the YouTube response puts the actual results in an items property, so use that too:
async search () {
const [cats, dogs] = await axios.all([
axios.get('...cats url...'),
axios.get('...dogs url...'),
]);
this.cats = cats.data.items;
this.dogs = dogs.data.items;
}