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

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.

Related

Why Axios response doesn't console log result?

I'm working on an backend API but at some point I need to get user data from another API. I am trying to use Axios to make http request in order to do that. The request return the result in the browser as expected but the problem is that I can't display console log in the terminal. It doesn't show anything even though I asked the program to do so. Is there a problem probably with my code?
Here is my code :
const axios = require('axios');
const AxiosLogger = require('axios-logger');
const instance = axios.create();
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
console.log(response.data);
return response.data
})
.catch(error => {
console.log(error);
});
});
};
I would suggest trying response.send to forward the axios response to your client like so:
module.exports = (router) => {
router.get('/profile', function(req, res) {
//random fake profile info
axios.get('https://randomuser.me/api/')
.then(response => {
console.log(response.data);
// Send the axios response to the client...
res.send(response.data)
})
.catch(error => {
console.log(error);
});
});
};

How to globally activate useEffect in React?

I am creating a chat application in React. I am using the useEffect-hook to update the messages (all it really does is fetch them from the JSON-server). I want them to be updated every time someone in the room sends a new message.
This is one alternative I have:
useEffect(() => {
fetch('http://localhost:8000/messages/')
.then(res => {
return res.json();
})
.then(data => {
data = data.filter((msg) => msg.room === room);
setData(data);
})
.catch(err => {
console.error(`Error: ${err}`);
})
divRef.current.scrollIntoView({ behavior: 'smooth' });
}, []);
"data" is a list of messages. This shows all the messages when you enter the room, but does not load when you pass a new message. Assumingly because of the empty list at the end. Therefore I tried this:
In another component, I have a variable "sent", which is set to true every time you send a message, like this:
const onSubmit = (e) => {
e.preventDefault();
const data = {author: user, body: msg, room }
setSent(true);
fetch(`http://localhost:8000/messages/`, {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data)
})
.then(response => {
response.json();
setSent(false);
})
.catch(err => console.error(`Error: ${err}`));
setMsg('');
}
So every time you send a message, it is set to 'true', and as soon as it has been successfully sent, it is set back to 'false'. I then passed it as a prop to the component I use useEffect:
<div className='chat-main'>
<Messages user={user} room={room} sent={sent} />
</div>
Then I put the "sent"-variable in the list at the bottom of the useEffect-hook. This updates the messages for the user who sends a message, but not for the others (because, of course, "sent" only changes if you send a message)
What can I do here? Is there a way?

I have a NodeJS backend I am developing to work alongside a ReactJS frontend but I keep getting a 500 error

I am testing my NodeJS backend using Insomnia and while it does work no problem in Insomnia I am getting a 500 error on the frontend every time. I was wondering if anyone maybe knew where this could be coming from if like I said it works just fine on my the endpoint testing program. Since it is a 500 error it is not very descriptive. Links can be shared if needed
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://exampleapi/api/login")
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.access_token);
props.history.push("/");
})
.catch(err => console.log(err.response)); };
So I figured it out it was an error in my post request would should have been included was
const handleSubmit = e => {
e.preventDefault();
console.log("cred username", creds.username);
axios
.post("https://mystery-doggo.herokuapp.com/api/login", creds)
.then(res => {
console.log(res.data);
localStorage.setItem("token", res.data.payload);
props.history.push("/");
})
.catch(err => console.log(err.response));
};
"creds" after the link and change res.data.access_token to res.data.payload

failed to send a get request using fetch api

I am trying to fetch some data from the server and I am using react.js
and the fetch api but a get that
SyntaxError: Unexpected token < in JSON at position 0
this is my code for fetching the data
componentDidMount() {
// fetch all categories from the server
fetch('http:localhost:5555/categories')
.then(res => res.json())
.then(categories => {
this.setState({ loading: false });
console.log(categories);
this.setState({ categories });
})
.catch(err => {
this.setState({ loading: false });
console.log(err);
});
}
any thoughts
I think the problem is in your fetch method and you write the url in the wrong form
try to change the url from
http:localhost:5555/categories
to
http://localhost:5555/categories
any try to fetch again

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