VueJS fetch promises - javascript

I have a component:
Vue.component('mail-list', {
props: ['userInbox'],
template:
`
<div>
<p>{{userInbox}}</p>
</div>
`
});
I want to print in p tag props content which is the result of created function
let options = {
el: "#app",
data: {
pollingId: null,
},
created: function() {
let users = fetch('/inbox')
.then(response => response.json())
.then(aJson => {return (aJson)})
this.userInbox = users
}
}
let vm = new Vue(options);
But this is only returning a promise which I can not work with.
PromiseĀ {<pending>}
Promise has this content:
{ '1':
Mail {
id: 1,
from: 'pep#mydomain.com',
to: 'mar#mydomain.com',
subject: 'Hi Mar',
body: 'This is a test from pep to mar',
timestamp: 1590647288599 },
'6':
Mail {
id: 6,
from: 'nil#mydomain.com',
to: 'mar#mydomain.com',
subject: 'By Mar',
body: 'This is a test from nil to mar',
timestamp: 1590647288599 } }
I have to display in p tag the from and subject attributes of each.

First, don't forget to register userInbox in your data.
Second, assign it in promise callback
let options = {
el: "#app",
data: {
pollingId: null,
userInbox: ''
},
created: function() {
let users = fetch('/inbox')
.then(response => response.json())
.then(aJson => {
this.userInbox = aJson
})
}
}
let vm = new Vue(options);

Related

How to push new data input to top on the list

hello how to push new data to the top list using vue.js and laravel, I tried but still failed, I hope someone can help with the problem.
this is my Controller
public function addComment()
{
$this->validate(request(), [
'comment' => 'required',
]);
$comment = [
'comment' => request()->comment,
'article_id' => request()->article_id,
'user_cid' => Auth::user()->user_cid,
];
$comment = ArticleComment::create($comment);
return new ArticleCommentResource($comment);
}
and this is my Vue.js Method
data() {
return {
data: [],
comments:[],
form: new Form({
comment: '',
article_id: this.articleid,
})
}
},
methods: {
onSubmit() {
this.showLoader = true
this.form.post('add-comment')
.then(response => {
console.log(response.article_id);
this.form.article_id = response.article_id;
});
},
}
how to handle it, thank you
I hope someone can help
Assuming your list simply loops through your comments array, you need to push the response at the first position of the list:
onSubmit() {
this.showLoader = true
this.form.post('add-comment')
.then(response => {
this.comments.unshift(response);
});
},
This assumes that response is the actual comment (I can't see into your form class).
<script>
import Form from 'form-backend-validation';
export default {
data:() => ({
form: new Form({
article_id: null,
}),
}),
mounted() {
this.fetch();
},
methods: {
async fetch() {
const response = await this.form.post('add-comment');
this.form.article_id = response.comment.article_id;
}
}
}
</script>
Please try this one.

How use a mutation function in a action function in Vuex?

I have this Vuex:
export default new Vuex.Store({
state: {
userInfo: {
nit_ID: { ID: '', Desc: '' },
userName: { ID: '', Desc: '' },
typeDocument: { ID: '', Desc: '' },
document: '',
},
globalPublicKey: 'ASDFGHJKL1234567890',
},
mutations: {
updateUserInfo(state, payload) {
state.userInfo = payload;
},
},
getters: {
userInfo: (state) => { return state.userInfo; },
},
actions: {
validateUserSession(context) {
var valido = false;
try {
let storageInfo = JSON.parse(
sjcl.decrypt(context.state.globalPublicKey, localStorage.userInfo)
);
if (localStorage.userToken === storageInfo.token) {
context.mutations.updateUserInfo(storageInfo);
valido = true;
}
} catch (e) {
console.error(e);
}
return valido;
},
},
})
But the problem is that I can't access to the mutation updateUserInfo(), I know that is easy to solved, only do the updateUserInfo process in my action, but the question is How can I use a mutation into a action?
In VueJS you can call a mutation from an action by calling context.commit, like this:
context.commit('mutationName', params)
params can be omitted if not parameters are passed to the mutation.
More on this here: vuex.vuejs.org/guide/actions.html
Actually you call a mutation from anywhere with a commit - but it's advised to use actions (so dispatch an action) that in turn commits the data (actually mutates the state).

Zapier JS conditional statement

I'm noob at JS, trying to write an APP for zapier. I have a test auth function that I can't get to fail when bad info is sent in.
Here is the test function:
require('should');
const zapier = require('zapier-platform-core');
const App = require('../../index');
const appTester = zapier.createAppTester(App);
describe('Triggers - Get Groups', () => {
zapier.tools.env.inject();
it('should get an array', done => {
const bundle = {
authData: { api_key: process.env.API_KEY },
inputData: {}
};
appTester(App.triggers['getgroup'].operation.perform, bundle)
.then(results => {
results.includes('id');
done();
})
.catch(results);
});
});
If successfull, a sample return should look like this:
{"id":1815,"name":"New Contacts","count":2}
A failure looks like this:
{"RESPONSE":"FAIL","REASON":"Invalid API key"}
Here is the getgroup function:
// Trigger stub created by 'zapier convert'. This is just a stub - you will need to edit!
const { replaceVars } = require('../utils');
const getList = (z, bundle) => {
let url = 'https://path.to/apisite?action=getGroups&apiKey={{api_key}}';
url = replaceVars(url, bundle);
const responsePromise = z.request({ url });
return responsePromise.then(response => {
response.throwForStatus();
return z.JSON.parse(response.content);
});
};
module.exports = {
key: 'getgroup',
noun: 'Getgroup',
display: {
label: 'Get Groups',
description: 'Triggers when loaded to pull groups.',
hidden: true,
important: false
},
operation: {
inputFields: [
{
key: 'group',
label: 'Groupget',
type: 'string',
required: false
}
],
outputFields: [
{
key: 'count',
type: 'string'
},
{
key: 'id',
type: 'string',
label: 'groupid'
},
{
key: 'name',
type: 'string',
label: 'groupname'
}
],
perform: getList,
sample: { count: 243, id: 27806, name: 'New Contacts' }
}
};
When I test auth on Zapier's website, I'd like auth to fail, and return the "REASON"
How do I do this?

React - Reset State stored from axios fetch

I am trying to reset the state for an object stored in my users array on click with handleDelete after I remove from the database. However, my state is not changing. I am able to log the current user with console.log('found: ' + this.state.users[i]). Basically, I have a table populated from my API and am trying to remove the row for the state without refreshing the page, but the state is not updating.
The constructor where my initial state is stored:
constructor(props) {
super(props);
this.state = {
users: []
}
this.handleDelete = this.handleDelete.bind(this);
};
Grabbing the API on mount:
componentDidMount() {
fetch('/myAPI')
.then(res => res.json())
.then(users => this.setState({ users }));
}
Mapping over data stored in state from fetch
render() {
return (
<tbody>
{this.state.users.map(user =>
<tr key={user.uniqueid}>
<td>{user.name}</td>
<td>{user.versions}</td>
<td>{user.type}</td>
<td>{user.hours}</td>
<td>{user.refresh}</td>
<td>{user.uniqueid}</td>
<td>{user.date}</td>
<td><Button onClick={this.handleDelete} data-id={user.uniqueid}><FaTrashO /></Button></td>
</tr>
)}
</tbody>
);
}
delete handler where I am TRYING to reset state for :
handleDelete(e) {
let dataId = e.target.getAttribute('data-id');
axios({
method: 'delete',
responseType: 'json',
url: '/myAPI',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Methods': "GET,HEAD,OPTIONS,POST,PUT"
},
data: { _id: dataId }
})
.then((response) => {
console.log(dataId + ' deleted with axios')
for (let i = 0; i < this.state.users.length; i++){
if (dataId === this.state.users[i]._id) {
let currentObj = this.state.users[i];
console.log('found: ' + this.state.users[i])
this.setState((prevState) => {
currentObj._id = ''
currentObj.date = '',
currentObj.hours = '',
currentObj.name = '',
currentObj.refresh = '',
currentObj.type = '',
currentObj.uniqueid = '',
currentObj.versions = ''
});
}
}
})
.catch((err) => {
throw err;
})
}
Example of what im calling from my API:
[
{
_id: "XJAbmHCX",
name: "an_example_2",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "XJAbmHCX",
date: "2018/01/08",
__v: 0
},
{
_id: "TOoIi7xS",
name: "test",
type: "A",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "TOoIi7xS",
date: "2018/01/09",
__v: 0
},
{
_id: "oeaigjesroigj",
name: "an_example_2_1",
type: "B",
versions: "10",
hours: "10",
refresh: "Yes",
uniqueid: "oeaigjesroigj",
date: "2018/01/08",
__v: 0
}
]
In the for loop of handleDelete, I simply sliced the user adn returned every object without the current ID to the state
for (let i = 0; i < this.state.users.length; i++){
if (dataId === this.state.users[i]._id) {
let users = this.state.users.slice();
users = users.filter(u => { return u._id !== dataId; });
this.setState({ users: users });
}
}

Angular 2 get json data from url

let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let ep = './data.json';
this.events = this.http
.get(ep, { headers: headers })
.map(res => res.json())
.map(({results}: { results: Data[] }) => {
return results.map((data: Data) => {
return {
title: data.title,
start: new Date(data.from),
colors.yellow,
};
});
});
Here is my code in Angular 2. I want to get data from a JSON file and show it in the angular-calendar.
Here is angular-calendar Demo: How can I do that?
You can make a service that contains the data for the calendar.
getList(): any
{
var date = new Date( '2017-01-12' );
var date2 = new Date( '2017-03-17' );
return (
[
{ title: 'Beauty And The Beast', start: date2, color: { primary: '#e3bc08', secondary: '#FDF1BA' } },
{ title: 'La La Land', start: date, color: { primary: '#e3bc08', secondary: '#FDF1BA' } }
]
)
}
Then you will have to remove the async pipe from the template.
Before:
[events]="(events | async ) || []
After:
[events]="(events) || []
Then call the service in the component:
fetchEvents()
{
this.events= this._data_Service.getList()
}
2. To get data.json file with Http you need to put the JSON file in the assets folder: ./assets/data.jsom, so that it can be accessed by the application: localhost:8080/data.json.
Then you simply make a get request.
fetchEvents(): void {
this.events = this.http
.get('../../assets/data.json') // the path may vary depending
// on your directory structure.
.map(res => res.json())
.map((results) => { // this might be different depending on
// your json and type definition.
return results.map((data: Data) => {
console.log({title: data.title,
start: new Date(data.from),
color: colors.yellow})
return {
title: data.title,
start: new Date(data.from),
color: colors.yellow,data
};
});
});
}// fetchEvents
Here is the JSON I used:
[
{"title":"La La Land","from":1490475722305},
{"title":"Beauty And The Beast","from":1490475722305}
]
finally, you can include the type definition in your component:
interface Data {
title: string;
from:string;
}
interface DataEvent extends CalendarEvent {
data: Data;
}

Categories

Resources