Vue JS console logging return an Observer - javascript

Here how are my datas in the store :
Here my code :
fetchNotifications() {
let notifications = {}
axios.get('/api/unreadNotifications')
.then(response => {
notifications = response.data
if(notifications) {
this.$store.commit("updateNotifications", notifications)
}
})
.catch(error => {
console.log()
});
},
checkDisplayQuestionnaire() {
console.log(this.$store.state.notifications)
},
If i console.log(response.data) in the .then of fetchNotifications(), datas are like this :
I tried to use JSON.parse(JSON.stringify(this.$store.state.notifications)) without success.
Anyone have an idea of the problem ? Thanks you.

Related

How to reload a GET request in created . Vue.js

i am getting the data from my rails API backend and what i want to do is reload that get request every 15s , so if something changes on a backend ( for example i make a post request to my backend in another route) it reloads and gets the current data .
My created :
created() {
if (!localStorage.signedIn) {
this.$router.replace("/");
} else {
this.$http.secured
.get("/api/v1/records")
.then(response => {
console.log(response.data);
this.records.splice(0, this.records.length - 1, ...response.data);
})
.catch(error => this.setError(error, "Something went wrong"));
this.$http.secured
.get("/api/v1/templates")
.then(response => {
this.templates = response.data;
})
.catch(error => this.setError(error, "Something went wrong"));
this.$http.secured
.get("/api/v1/data")
.then(response => {
this.datas = response.data;
})
.catch(error => this.setError(error, "Something went wrong"));
}
},
Could you help me with implementing a setInterval to my get requests?
thanks
Try to use the setInterval, like:
mounted() {
this.intervalData = setInterval(this.getdata, 15000)
},
destroyed() {
clearInterval(this.intervalData)
},
methods: {
getData() {}
},
More smart solution could be: use POST request in nuxt proxy server or in your backend, like axios.post('/data', payload) and connect the websockets, you can use pusher for that. The final logic is: user add some data => post to server => server emits the websockets event => vuex listen to the event and the data will be reactive in all tabs.

VueJS and axios - how to access data in a post request

I have got data like this:
data: () => ({
input: {
username: "",
password: ""
}
}),
and make a post request like this:
loggin_in() {
if (this.input.username != "" && this.input.password != "") {
console.log(this.input.username);
axios
.post("http://localhost:5000/login", {
email: this.input.username,
password: this.input.password
})
.then(function(data) {
console.log(data);
})
.catch(function(error) {
console.log(this.input.username);
});
}
}
Logging the first this.input.username works, but after that, I have no idea how to access the data. this seems to be undefined.
Uncaught (in promise) TypeError: Cannot read property 'input' of undefined
I dont know why the context of this changes here and donĀ“t get how to access my data. Can anybody explain me whats going on and help me with this?
In the callback you have to bind this or use an arrow function:
.then(function(data) {
console.log(data);
})
to
.then((data) => {
console.log(data);
console.log(this);
})

having difficult in debugging some functions where the author mainly did axios request

I am reading a codebase where I see this way of writing code. I am having difficulty in introducing console logs.
I would like to do a console log for the entire URL that is being sent and also the response and error.
const fetchSportsFanDetails = (sportsFanId, authToken) =>
axios
.get(`${API.BASE_URL}SportsFans/${sportsFanId}/profile`, {
headers: {
...getAuthHeaderWithContentType(authToken, "JSON")
}
})
.then(resp => (resp && resp.data ? resp.data : null));
I am having difficulty in debugging this piece of written code. Can anyone please assist me in this regard?
Try bellow. The issue is that the {} of the function are omited since it does one line, which makes it hard to introduce new lines without adding it first.
const fetchSportsFanDetails = (sportsFanId, authToken) => {
let url = `${API.BASE_URL}SportsFans/${sportsFanId}/profile`;
console.log(`url: ${url}`)
axios
.get(url, {
headers: {
...getAuthHeaderWithContentType(authToken, "JSON")
}
})
.then(resp => (resp && resp.data ? resp.data : null));
}
edit for response, replace the .then with
.then(resp => {console.log(resp); (resp && resp.data ? resp.data : null)});
Basically you are working with arrow functions https://www.sitepoint.com/es6-arrow-functions-new-fat-concise-syntax-javascript/

Why fetch isn't working second time?

This is a very very annoying thing, i'm trying to solve it for hours right now. Here's the code:
//ExpressJS code
app.post('/newname', (req, res) => {
const {name, type, id} = req.body;
console.log(name, type, id)
knex('fl').insert({
name, type, id,
...type === 'category'? {timeValue: req.body.timeValue, timeType: req.body.timeType} : {}
})
.then(() => {
console.log("bar");
return knex('fl').select('*').where('status', 'available')})
.then(data => res.json(data))
.catch(err => console.log(err))
})
//React code
possibleName = (event) => {
this.setState({
possibleName: event.target.value
})
console.log(this.state.possibleName)
}
complete = () => {
if(Boolean(this.state.possibleName)){
console.log(this.state.possibleName)
fetch('http://localhost:3001/newname', {
method: 'post',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
name: this.state.possibleName,
type: this.state.type,
id: this.props.id,
...this.state.type === 'category'? {timeValue: this.props.timeValue, timeType: this.props.timeType}:{}
})
})
.then(res => res.json())
.then(data => {
console.log("foo");
this.props.dispatch(getAction(data));
this.setState({
create: 'none',
zindex: 0,
possibleName: ''
})
})
.catch(err => console.log(err))
}
}
//...
//...
<input type='text' value={this.state.possibleName} onChange={this.possibleName}/>
<div onClick={this.complete}></div>
So... The first time the div is clicked, everything works fine. All the logs are in the console. The second time, the complete()'s first log happens, but it seems like the fetch isn't happening. What's the reason? Something blocks the second fetch? If i try it with Postman, with the same format of req.body, everything works fine every time i try it. So i don't know what will be the problem.
Another thing that might the source of the problem i think, is that there's a dispatch. It's possible that redux don't let the fetch to finish? I mean the first fetch begins, but not completes, so if i fetch second time, it get into query, and starts when the fetch before finishes?

update dom to render results after api request

SOLVED: by adding this.tasks = resp.data in the functions so that it updates to the new state...
i'm currently working on a simple todo-list app in vuejs and i'm looking for a way to update the dom in a smooth way after doing the api request. The only way i've been able to display the changes directly after they've been made is by putting location.reload() in the response. I've been looking over some examples and guides and people seem to be able to do this with .bind(), but it's not working for me and i'm not content with the page flashing on every change you make.
//deletePost works for displaying changes but i don't want the page to flash on every update
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
location.reload();
})
.catch((err) => {
console.log(err)
})
},
//this is how i've seen people doing it, but it's not working for me.
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
Any ideas?
You shold have an array of tasks in your Vue component. Sending an http request deletes the resource from the server, but not locally. To delete the resource inside your component you'll need to do it in the .then() part for example like this:
data() return {
tasks: []
},
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
// Here we delete the task from the component locally
// Note that we only want to delete it if the request is successful
let index= this.tasks.find(task => task.id === id)
this.tasks.splice(index,1);
})
.catch((err) => {
console.log(err)
})
},
//this is how i've seen people doing it, but it's not working for me.
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
Thanks for replying to my first post here so quickly, of course i should've provided the whole script and not just the api request...
data () {
return {
tasks: [],
formValue: '',
selected: ''
}
},
created () {
this.fetchData()
},
watch: {
'$route': 'fetchData',
},
methods: {
fetchData () {
axios.get('http://localhost:3000/tasks')
.then((resp) => {
this.tasks = resp.data
console.log(resp.data)
})
.catch((err) => {
console.log(err)
})
},
deletePost(id) {
axios.delete(`http://localhost:3000/tasks/${id}`)
.then((resp) => {
console.log(resp.data)
// Here we delete the task from the component locally
// Note that we only want to delete it if the request is successful
let index= this.tasks.find(task => task.id === id)
this.tasks.splice(index,1);
})
.catch((err) => {
console.log(err)
})
},
//updates post status
updatePost(selected, id) {
axios.put(`http://localhost:3000/tasks/${id}`,{ status: selected } )
.then(function(response){
console.log('saved successfully')
}.bind(this));
}
},
}

Categories

Resources