Save API data into an array with vue.js - javascript

I need help doing this. I want to save the user list from the API to an array (called "name"). How can I do this? I tried this forEach but can't make it work. Thanks!
Edit: I wraped the function, still not working.
import axios from 'axios'
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {
}))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}

From the code above I'm assuming the data in this.info in correct. The problems I see in your code are:
1.
.then(response => (this.info = response.data))
.then(() => info.data.forEach(element => {
}))
info looks to be undefined. I assume this should be this.info.
.then(response => (this.info = response.data))
.then(() => this.info.data.forEach(element => {
}))
Or if you're using the arrow function syntax and returning an assignment expression, you can use
.then(response => (this.info = response.data))
.then(info => info.data.forEach(element => {
}))
Which I don't really recommend, since some linting rules disallow returning assignment expressions (for good reasons). To chain a promise that relies on this implicit language behavior can make code less easily understood.
2.
What forEach does matters. Vue's reactivity does not pick up certain assignment syntax, i.e. this.name[i] = element. You can use array methods like push, but I recommend you use functional programming operators, like map and filter:
.then(() => (this.name = this.info.data.map(element => {
})))

Maybe the this reference is not correct, because on callback methods is on another context, try it:
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
var self = this
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then(response => (self.info = response.data))
.then(info.data.forEach(element => {
});)
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}

you forgot to encapsulate the callback into a function receiving the info variable,
try this:
import axios from 'axios'
export default {
data () {
return {
info: null,
name: []
}
},
mounted () {
axios
.get('http://localhost:3000/api/users/', {mode: 'no-cors'})
.then((response) => response.data.forEach(element => {
}))
.catch(error => {
console.log(error)
this.errored = true
})
.finally(this.loading = false)
}
}

Related

Vue.js 3.0: Read and set object properties from method

I am learning and creating a Vue application. When I try setting the properties, I get an error like this, Cannot read property 'Selected.type' of undefined
This is how I try to do it:
<script>
export default {
data() {
return {
info: {},
Selected: {
type: '',
country: '',
}
};
},
methods: {
fetchData () {
fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
.then( resp => resp.json())
.then((data) => (this.info = data))
.then(function (data) {
console.log(data.organisasjonsform.beskrivelse);
this.Selected.type=data.organisasjonsform.beskrivelse;
})
.catch(err => console.error(err))
}
},
mounted() {
this.fetchData();
},
};
</script>
Why I am getting this error? I am new to VueJS. Can someone please help me out here?
This is because this refer to the execution context of the callback-function, not the Vue component. It is caused by using the function-keyword to declare your callback instead of the newer () => {} syntax.
If you change your code to:
fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
.then( resp => resp.json())
.then((data) => (this.info = data))
.then((data) => {
console.log(data.organisasjonsform.beskrivelse);
this.Selected.type=data.organisasjonsform.beskrivelse;
})
It should work.
An alternative syntax, is to capture the this context in a variable within the closure of your fetchData-method
fetchData () {
const self = this;
fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
.then( resp => resp.json())
.then((data) => (this.info = data))
.then(function (data) {
console.log(data.organisasjonsform.beskrivelse);
self.Selected.type=data.organisasjonsform.beskrivelse;
})
.catch(err => console.error(err))
}
This should work, I didn't try it but it's obvious.
you have to add the 'this' before Selected.type to access it.
Edit:
My bad, I totally forgot about the function context. That's what happens when you don't run your code before posting, i guess.
fetch(`https://data.brreg.no/enhetsregisteret/api/enheter/983609155`)
.then( resp => resp.json())
.then((data) => (this.info = data))
.then((data) => {
console.log(data.organisasjonsform.beskrivelse);
this.Selected.type=data.organisasjonsform.beskrivelse;
})
.catch(err => console.error(err))
}

Cannot read property 'then' of undefined for axios wrapper

I have a bit of a similar issue like this but I can't seem to get it right. I know I have to return a promise and I think I do, although it's still not accepted. Here is my wrapper function for axios calls:
export const callGraph = (url, token) => {
return axios.get(url, {headers: { Authorization: `Bearer ${token}` }})
}
This is the function that invokes callGraph that in turn should return a Promise:
export const getGraphProfile = () => {
if (auth.getAccount()) {
auth.getToken(loginRequest)
.then(response => {
return callGraph(graphConfig.graphMeUrl, response.accessToken)
})
.catch(error => { console.log(error) })
}
}
As you can see I explicitly request return callGraph so I can use it like this:
getGraphProfile()
.then(response => { console.log('givenName ', response.data.givenName) })
.catch(error => console.log(error))
For one reason or another I'm still missing something. Thank you for your help.
You should return the axios promise
export const getGraphProfile = () => {
if (auth.getAccount()) {
return auth.getToken(loginRequest)
.then(response => {
return callGraph(graphConfig.graphMeUrl, response.accessToken)
})
.catch(error => { console.log(error) })
}
}

Using RxJS and axios, how do you fetch data onClick in React component?

I'm struggling with how to fetch data using RxJS and axios onClick in a React component. But getting closer, I think. Any attempts I've tried either run when component mounts, not onClick, or don't run at all even onClick.
Basically, how to call onClick and how to pass a payload. There just seems to be nothing online to explain this which i would expect to be a common situation.
const MyComponent = () => {
const [data, setData] = useState(null);
const getData$ = new Subject(observer => {
axios
.post(`/my-url/`, **how to get payload to here**)
.then(response => {
observer.next(response.data);
observer.complete();
})
.catch(error => {
observer.error(error);
});
});
useEffect(() => {
const subs = getData$.subscribe({
next: res => setData(res),
});
return () => subs.unsubscribe();
}, []);
return (
<Button onClick={() => getData$.next(payload)} />
);
};
Any help appreciated.
you can pass in the payload in getData like this
const getData$ = (payload) => new Subject(observer => {
axios.post(`/my-url/`, payload)
.then(response => {
observer.next(response.data);
observer.complete();
})
.catch(error => {
observer.error(error);
});
});
This basically just creates an anonymous function called getData that returns your Subject. It's equivalent to this:
const getData$ = function (payload) {
return new Subject(observer => {
axios.post(`/my-url/`, payload)
.then(response => {
observer.next(response.data);
observer.complete();
})
.catch(error => {
observer.error(error);
});
});
};

How to fetch data from multiple db from the node.js in frontend react.js

I have the below code, where I have to get data from all the files in the same DB. Node.js is running at the backend. When I try the below code, I always get the last fetch, can anyone please help me how to fix this.
The below is from the react JS frontend.
componentDidMount() {
console.log("This Worked Sucessfully")
this.getDataFromDb();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getDataFromDb, 1000);
this.setState({ intervalIsSet: interval });
}
}
getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/passed')
.then(data => data.json())
.then(res => this.setState({ passed: res.data }));
};
getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/failed')
.then(data => data.json())
.then(res => this.setState({ failed: res.data }));
};
getDataFromDb = () => {fetch('http://172.24.78.202:3001/api/all')
.then(data => data.json())
.then(res => this.setState({ data2: res.data }));
};
render() {
const primaryColor = getColor('primary');
const secondaryColor = getColor('secondary');
const { passed, failed, data2 } = this.state
From what I see by your code, you seem to be re-writing your goGetDataFromDB two times. Try changing the names of each function or, the way you call them. You can also take advantage of Promise.all to group the results of each call into a single return handle.
Check this link for the documentation of Promise.all
You could refactor your current code to something like this:
class MyComponent extends React.Component {
componentDidMount() {
this.getDataFromDb();
if (!this.state.intervalIsSet) {
let interval = setInterval(this.getDataFromDb, 1000)
this.setState({intervalIsSet: true })
}
}
getDataFromDb = () => {
Promise.all([
'http://172.24.78.202:3001/api/passed',
'http://172.24.78.202:3001/api/failed',
'http://172.24.78.202:3001/api/all'
].map(url => (
fetch(url)
.then(data => data.json())
.then(res => res.data)
)
)).then(([passed, failed, data2]) =>
this.setState({ passed, failed, data2 })
);
}
render() {
//...
}
}
I tried to keep as much as your code as possible so you could notice the differences.
I hope this helps.

receiving data from api but cant setState

For some reason, I am unable to update the state of my component with the data from my fetch request.
When I console.log, I can see that I am getting the data. I'm not sure what this could be
If this is a noob issue, please bear with me. I'm still learning.
Here is my code:
import React, { Component } from "react";
class Nav extends Component {
state = {
searchTerm: "",
posts: []
};
getPost = e => {
e.preventDefault();
const val = e.target.value;
this.setState({ searchTerm: val }, () => {
if (val !== "") {
fetch(
`http://www.reddit.com/search.json?q=${val}&sort=relevance&limit=25`
)
.then(res => res.json())
.then(data => console.log(data.data))
//.then(data => this.setState({ posts: data.data }))
//.then(console.log(this.state.posts))
.catch(err => console.log(err));
}
});
};
Actually everything is right and going well, just your logging is wrong.
.then(console.log(this.state.posts))
That logs the state now and passes the result of console.log() (undefined) to the .then chain as a callback which is obviously wrong. I guess you meant:
.then(() => console.log(this.state.posts))
But that still won't work as setState does not trigger a state update immeadiately, but somewhen. After that it calls the second argument as a callback, so you should log then:
.then(data => this.setState({ posts: data.data }, () => {
console.log(this.state.posts);
}))
Altogether:
const response = fetch(
`http://www.reddit.com/search.json?q=${val}&sort=relevance&limit=25`
).then(res => res.json());
// PS: I would not build up a chain if the logic is not really "chained"
response.then(data => console.log(data.data));
response.then(data => this.setState({ posts: data.data }, () => console.log(this.state.data)));
response.catch(err => console.log(err));

Categories