data not match with response from axios vuejs - laravel

im new in vuejs
I have button to get detail data like this:
<button class="btn btn-sm btn-primary" title="Detail" #click="showDetail(task.id)"><span class="fa fa-eye"></span></button>
and the script like this
export default {
data(){
return {
tasks: [],
taskDetail: [],
categoryName: "",
typeName: "",
detailExist: false
}
},
created(){
this.getTasks()
},
methods: {
getTasks(){
axios.get("/task-lists/")
.then(res => {
this.tasks = res.data.data
})
},
showDetail(id){
this.detailExist = false
axios.get("/task-detail/"+id)
.then(res => {
console.log(res)
this.taskDetail = res.data.data
this.detailExist = true
this.collectCategory(this.taskDetail.category)
this.collectType(this.taskDetail.type)
}).catch(error => {
console.log(error)
})
},
startTask(id){
axios.post('/start-task', {id: id, status: 1})
.then(res => {
this.getTasks()
console.log(res.data)
})
},
finishDev(id){
axios.post('/finish-dev', {id: id, status: 2})
.then(res => {
this.getTasks()
})
},
collectCategory(val){
switch (val) {
case 2:
this.categoryName = 'Normal';
break;
case 3:
this.categoryName = 'Emergency';
break;
default:
this.categoryName = 'Standard';
break;
}
},
collectType(val){
switch (val) {
case 2:
this.typeName = 'New Feature';
break;
case 3:
this.typeName = 'Bug Fixing';
break;
default:
this.typeName = 'Revamp';
break;
}
}
}
}
But i got confuse because there is a difference between what i get in res in axios and response api if i see from browser > inspect > network. In browser i get like this
{
"data": {
"id": 1,
"task_no": "RFC123XYZ",
"task_name": "Task View",
"mandays": 2,
"start_date": "2021-10-12",
"status": 2,
"category": 2,
"type": 2,
"description": null,
"cycle": [],
}
}
but in axios i always get value 1 in "status" when i console.log(res).

Related

Laravel Vue.js after patch request get doesn't load all the data

I want to dynamically hide the "Sign up" button when all the places for the event have been taken. I also update the list of signed-up users.
After clicking on the Signup button the data is saved correctly on the backend but the frontend displays only the pictures of players and there are the usernames. After refreshing the page I can see the usernames and photos. How can I fix my code so all the data will be displayed after the patch?
I'm using 2 Vue components:
AddPlayesComponent
<template>
<div>
<form v-if="freePlaces == true || freePlaces == 1" #submit.prevent="submit()">
<button type="submit" name="participant">Sign up</button>
</form>
</div>
</template>
<script>
export default {
data() {
return {
freePlaces: "",
url: "",
}
},
created() {
this.getUrl();
this.fetchStatus();
this.showForm();
},
methods: {
getUrl() {
let id = window.location.href.split('/').pop();
this.url = "/events/" + id + "/team" ;
},
fetchStatus() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/availabilty').then((response) => {
this.freePlaces = response.data;
})
},
showForm() {
Echo.channel('team-list-count')
.listen('.players-allowed', (data) => {
this.freePlaces = data.playersAllowed;
})
},
submit() {
axios.post(this.url, {
_method: 'patch'
})
.then(response => {
console.log(response.data);
})
.catch(e => {
console.log("Error is");
console.log(e.data);
});
}
},
computed: {
availabilePlaces() {
return this.freePlaces;
return this.url;
}
}
}
</script>
and TeamListComponent
<template>
<div>
<div v-for="(player, key) in team">
<img :src="'/storage/' + player.profil_photo" alt="profile picture " >
{{ player.username }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
team: [],
}
},
created() {
this.fetchTeam();
this.AddNewPlayerListener();
this.DeleteNewPlayerListener();
},
methods: {
fetchTeam() {
let id = window.location.href.split('/').pop();
axios.get('/events/'+ id + '/team').then((response) => {
this.team = response.data;
})
},
AddNewPlayerListener() {
Echo.channel('team-list')
.listen('.updated-team', (data) => {
this.team = data.team;
})
},
DeleteNewPlayerListener(){
Echo.channel('team-list-delete')
.listen('.updated-team', (data) => {
this.team = data.team;
})
}
},
computed: {
teamList() {
return this.team;
}
}
}
</script>
Controller contains this funcion:
protected function addPlayer($event) {
$registered = $event->registered_participants;
$registered++;
$allowed = $event->allowed_participants;
if($allowed <= $registered) {
$playersAllowed = false;
event(new ParticipantsCounter($playersAllowed));
if($allowed < $registered) {
return redirect()->route('event.show', [ 'event' => $event ]);
}
}
$event->registered_participants = $registered;
$event->save();
$profile = auth()->user()->profile;
$profile->participate()->syncWithoutDetaching([$event->id], false);
$team = $event->participants()->get();
foreach ($team as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
}
event(new NewParticipant($team));
return redirect()->route('event.show', [ 'event' => $event ]);
}
Data after patch request:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg" }
Data after refreshing page:
{ "id": 5,
"created_at": "2022-04-12T20:35:03.000000Z",
"updated_at": "2022-04-12T20:35:40.000000Z",
"user_id": 5,
"name": "Marlena",
"familyname": "Test",
"location": "Amblève",
"gender": "x",
"birthdate": "2000-12-12",
"favorite_sport": "hockey",
"biography": "Here comes biography",
"profil_photo": "profiles/kbERb4XrXnu379rtCcyWwb46pOq9UQAtkTKgr42W.jpg",
"username": "testUser",
"pivot": {
"event_id": 1,
"profile_id": 5,
"created_at": "2022-04-25T15:27:37.000000Z",
"updated_at": "2022-04-25T15:27:37.000000Z" }
}
Update:
I solved it by creating an empty array where I push each player after adding a username.
$oldTeam = $event->participants()->get();
$team = [];
foreach ($oldTeam as $player) {
$user = User::where('id', $player->user_id)->first();
$player->username = $user->username;
array_push($team, $player);
}

Apollo client's offsetLimitPagination requests for graphql server although the data is available in cache

Whenever I navigate to different pages, data will be added to Apollo's cache. but when I navigate to previous pages, although the data is available in cache. Apollo issues a network request to graphql server.
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
users: {
...offsetLimitPagination(),
read(existing, { args }) {
return (
existing &&
existing.slice(
args?.offset,
args?.offset + args?.limit
)
)
},
}
},
},
},
})
const client = new ApolloClient({
uri: "https://api.spacex.land/graphql/",
cache,
connectToDevTools: true,
})
And my component:
const Users: React.FC = () => {
const [offset, setOffset] = useState(0)
const { loading, data, error, fetchMore } = useUsersQuery({ \\ Generated via graphql-code-gen
variables: { offset, limit: 2 },
})
const fetchMoreHandler = (): void => {
const currentLength = data?.users.length || 0
fetchMore({
variables: { offset: offset + currentLength, limit: 2 },
}).then(() => {
setOffset((ofsset) => ofsset + currentLength)
})
}
const fetchPrevHandler = (): void => {
let currentLength = data?.users.length || 0
if (currentLength === 0) {
currentLength = 2
}
fetchMore({
variables: { offset: offset - currentLength, limit: 2 },
}).then(() => {
setOffset((ofsset) => ofsset - currentLength)
})
}
if (loading) {
return <div>Loading....</div>
}
if (error) {
return <div>Something went wrong!</div>
}
return (
<div className={classes.root}>
{offset > 0 && (
<button type="button" onClick={fetchPrevHandler}>
Prev
</button>
)}
<div>
{data?.users.map((user) => (
<div key={user.id}>
<h6>{user.name}</h6>
</div>
))}
</div>
{(data?.users.length || 0) > 0 && (
<button type="button" onClick={fetchMoreHandler}>
Next
</button>
)}
</div>
)
}
export default Users
And here's the query:
query Users($offset: Int, $limit: Int) {
users(offset:$offset, limit: $limit, order_by:[{timestamp:desc}]) {
id
name
rocket
timestamp
twitter
}
}
When I navigate my cache looks like this:
_APOLLO_CLIENT_.cache.data.data:
{
"users:a75bf714-30e4-4219-8335-e413f8f127ef": {
"id": "a75bf714-30e4-4219-8335-e413f8f127ef",
"__typename": "users",
"name": "HI",
"rocket": "FRIENDS",
"timestamp": "2021-12-22T18:38:09.805832+00:00",
"twitter": null
},
"users:c2317843-8481-4cb6-87e1-16d8f4aa7092": {
"id": "c2317843-8481-4cb6-87e1-16d8f4aa7092",
"__typename": "users",
"name": "simeooone",
"rocket": "tha_rocket",
"timestamp": "2021-12-22T16:14:50.431972+00:00",
"twitter": "#galfh"
},
"ROOT_QUERY": {
"__typename": "Query",
"users": [
{
"__ref": "users:a75bf714-30e4-4219-8335-e413f8f127ef"
},
{
"__ref": "users:c2317843-8481-4cb6-87e1-16d8f4aa7092"
},
{
"__ref": "users:f6358c49-7ce3-491e-8103-48e9e4b847cd"
},
{
"__ref": "users:a04c9b78-3406-4585-ba16-0a4c540fdc23"
}
]
},
"users:f6358c49-7ce3-491e-8103-48e9e4b847cd": {
"id": "f6358c49-7ce3-491e-8103-48e9e4b847cd",
"__typename": "users",
"name": "aemilio",
"rocket": "yo_mum",
"timestamp": "2021-12-22T16:11:14.728876+00:00",
"twitter": "#yo_mum"
},
"users:a04c9b78-3406-4585-ba16-0a4c540fdc23": {
"id": "a04c9b78-3406-4585-ba16-0a4c540fdc23",
"__typename": "users",
"name": "",
"rocket": "oy",
"timestamp": "2021-12-22T16:10:24.420815+00:00",
"twitter": "asd"
}
}
And when I navigate back to show these exact items, still apollo makes network requests!
For other's that are new to Apollo like me and have this question, I figured out that fetchMore function always force network request no matter what. That's by design. If you want to read from cache you shouldn't use fetchMore and do something like this instead:
const [offset, setOffset] = useState(0)
const { loading, data, error } = useUsersQuery({
variables: { offset, limit: 2 },
})
const fetchMoreHandler = (): void => {
const currentLength = data?.users.length || 0
setOffset((ofsset) => ofsset + currentLength)
}
const fetchPrevHandler = (): void => {
let currentLength = data?.users.length || 0
if (currentLength === 0) {
currentLength = 2
}
setOffset((ofsset) =>
ofsset - currentLength < 0 ? 0 : ofsset - currentLength
)
}
and this would be your instance of InMemoryCache:
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
users: {
...offsetLimitPagination(),
read(existing, { args }) {
let res
if (existing) {
res = existing.slice(
args?.offset,
args?.offset + args?.limit
)
}
return res && res.length === args?.limit
? res
: undefined
},
},
},
},
},
})

How to loop through JSON Object in vue js

I am working on vue.js and backend is laravel. I am new to these technologies.
I am trying to display data in parent and child rows in a table base on vue material syntax.
My Laravel controlller function contains the code
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get();
I am trying to get data grouped by task_status. For each task status there are multiple rows.
My JSON is like below -
[
{
"tasks_status": "Completed Task",
"subrow": "{\"id\":\"4\",\"name\":\"d1\"}"
},
{
"tasks_status": "My Tasks",
"subrow": "{\"id\":\"2\",\"name\":\"b1\"},{\"id\":\"7\",\"name\":\"g1\"}"
}
]
Online JSON Parser validates it.
in Vue Front end I try to display this JSON data using 2 for loops Like below
<md-table v-model="searched" md-sort="name" md-sort-order="asc" md-fixed-header class="table-sort">
<md-table-toolbar>
<div class="md-toolbar-section-start">
<h1 class="md-title">Tasks</h1>
</div>
<md-field md-clearable class="md-toolbar-section-end">
<label for="Tasks">Tasks</label>
<md-select v-model="fieldsSearchTerm.searchTermForDataTable" name="search" id="search" #input="searchOnTable" >
<md-option value="">All Tasks</md-option>
<md-option value="My Tasks">My Tasks</md-option>
<md-option value="Organization Tasks"
>Organization Tasks</md-option
>
<md-option value="Received Tasks"
>Received Tasks</md-option
>
<md-option value="Completed Task"
>Completed Task</md-option
>
<md-option value="Incomplete Tasks"
>Incomplete Tasks</md-option
>
<md-option value="Sent Tasks">Sent Tasks</md-option>
</md-select>
</md-field>
<md-field md-clearable class="md-toolbar-section-end">
<b-button class="btn btn-danger modal-btn" block #click="changeStatusToDone">Done</b-button>
</md-field>
</md-table-toolbar>
<md-table-empty-state
md-label="No data found">
</md-table-empty-state>
<md-table-row slot="md-table-row" v-for="rowHeading in searched" >
<md-table-cell md-label="Task Name" md-sort-by="name">{{ rowHeading.tasks_status }}</md-table-cell>
<md-table-cell md-label="Task Status" md-sort-by="tasks_status"></md-table-cell>
<md-table-cell md-label="Due Date" md-sort-by="due_date"></md-table-cell>
<md-table-cell md-label="Priority" md-sort-by="priority"></md-table-cell>
<md-table-cell md-label="Actions" md-sort-by="">
</md-table-cell>
</md-table-row>
<md-table-row slot="md-table-row" v-for="subRowElements in rowHeading.subrow">
<md-table-cell md-label="" md-sort-by="" >
</md-table-cell>
<md-table-cell colspan=4 md-label="Task Name" md-sort-by="name">hi {{ subRowElements }}</md-table-cell>
</md-table-cell>
</md-table-row>
</md-table>
In My JS I have code like this below
import Cookies from 'js-cookie'
import axios from "axios"
import Vue from 'vue'
import VueResource from 'vue-resource'
import Form from 'vform'
const toLower = text => {
return text.toString().toLowerCase()
}
const searchByName = (items, term) => {
if (term) {
return items.filter(item => toLower(item.tasks_status).includes(toLower(term)))
}
return items
}
export default {
name: 'TableSearch',
components: {
},
data() {
form: new Form({
tasks_statusUpdate: '',
nameUpdate: '',
priorityUpdate: '',
task_descriptionUpdate: '',
dueDateUpdate: '',
taskAssignedToUserUpdate: '',
_token: Cookies.get('token')
})
return {
goods: [],
fieldsUpdate: {
tasks_statusUpdate: "",
nameUpdate: "",
priorityUpdate: "",
task_descriptionUpdate: '',
dueDateUpdate: "",
taskAssignedToUserUpdate: "",
_token: Cookies.get('token'),
},
fieldsView: {
tasks_statusView: "",
nameView: "",
priorityView: "",
task_descriptionView: '',
dueDateView: "",
taskAssignedToUserView: "",
userNameView: "",
},
fieldsTaskDone: {
tasks_status: 1,
},
fieldsSearchTerm: {
searchTermForDataTable: '',
},
fieldsCheckBox: {
cboTaskName: true,
cboTaskStatus: true,
cboDueDate: true,
cboPriority: true,
},
isOpen: true,
rows: null,
allUsersUpdate: [],
searched: [],
rowHeading:[],
subRowElements:[],
users: [
{
id: 1,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 2,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 3,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 4,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 5,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 6,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 7,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 8,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 9,
name: "Shawna Dubbin",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
{
id: 10,
name: "Shawna vishal",
email: "sdubbin0#geocities.com",
date: "20/02/2021",
priority: "High"
},
],
rows: [],
editing_record_id: 0,
view_record_id: 0,
checkedTaskIDs: [],
dynamicColumn: [],
}
},
methods: {
newUser () {
window.alert('Noop')
},
searchOnTable () {
this.makeGetRequest();
this.searched = searchByName(this.rows, this.search)
},
fnDynamicColumns: function(e){
if (e.target.checked) {
console.log(e.target.value)
}
},
check_task_id: function(e) {
if (e.target.checked) {
console.log(e.target.value)
}
},
changeStatusToDone () {
axios
.post("api/v1/tasks/"+this.checkedTaskIDs+"/complete",
this.fieldsTaskDone
)
.then(response => {
alert("Task Done!");
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
},
async makeGetRequest() {
console.log("makeGetRequest begin ");
var fnRows = [];
await axios.get('api/v1/tasks', {
params: {
searchTermForDataTable: this.fieldsSearchTerm.searchTermForDataTable
}
})
.then((response) => {
this.rows = response.data;
fnRows = response.data;
console.log("inside axios > makeGetRequest" + JSON.stringify(this.rows));
});
this.searched = this.rows
console.log("makeGetRequest later " + this.searched);
},
async getAllUsers() {
console.log("table > getAllUsers begin ");
await axios.get('api/v1/getallusers')
.then((response) => {
this.allUsersUpdate = response.data;
});
console.log("table > outside axios user11" + this.allUsersUpdate);
},
submitUpdateForm() {
console.log(this.fieldsUpdate);
console.log(Cookies.get('token'));
axios
.put("api/v1/tasks/"+this.editing_record_id,
this.fieldsUpdate
)
.then(response => {
alert("Task Updated!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
console.log("ppppnnnnnn");
},
async getTask() {
await axios.get('api/v1/tasks/'+this.editing_record_id)
.then((response) => {
this.fieldsUpdate.tasks_statusUpdate = response.data[0].tasks_status;
this.fieldsUpdate.nameUpdate = response.data[0].name;
this.fieldsUpdate.taskAssignedToUserUpdate = response.data[0].user_id;
this.fieldsUpdate.priorityUpdate = response.data[0].priority;
this.fieldsUpdate.task_descriptionUpdate = response.data[0].task_description;
if(response.data[0].due_date !== null)
{
this.fieldsUpdate.dueDateUpdate = response.data[0].due_date;
}
console.log("getTask With Join" + JSON.stringify(response.data[0]));
});
console.log("getTask With Join" + JSON.stringify(this.fieldsUpdate));
},
showUpdateModal(id) {
this.editing_record_id = id;
this.getTask();
this.$bvModal.show('taskUpdateModal')
},
softDeleteTask(id) {
if(confirm("Are you sure, you want to delete, this task?")){
axios
.delete("api/v1/tasks/"+id)
.then(response => {
alert("Task Deleted!");
//this.fields = {};
})
.catch(error => {
console.log(error);
});
this.makeGetRequest();
}
},
async getTaskForView() {
await axios.get('api/v1/tasks/'+this.view_record_id)
.then((response) => {
this.fieldsView.tasks_statusView = response.data[0].tasks_status;
this.fieldsView.nameView = response.data[0].name;
this.fieldsView.taskAssignedToUserView = response.data[0].user_id;
this.fieldsView.priorityView = response.data[0].priority;
this.fieldsView.task_descriptionView = response.data[0].task_description;
this.fieldsView.dueDateView = response.data[0].due_date;
this.fieldsView.userNameView = response.data[0].userName;
});
console.log("getTask" + JSON.stringify(this.fieldsView));
},
showViewModal(id) {
this.view_record_id = id;
this.getTaskForView();
this.$bvModal.show('taskViewModal')
},
},
created () {
console.log("inside created()1");
this.makeGetRequest();
this.getAllUsers();
console.log("outside axios" + this.rows);
enter code here
console.log("inside created() 2");
},
mounted() {
console.log("inside mounted()")
},
}
Can Anybody suggests a way to get valid JSON from controller and display it with correct loops in vue.js page. Thanks in advance.
I think you should use something like this in your Laravel controller, and then it would be easier to use loop to output json
$tasks = Task::select('tasks_status', DB::raw("group_concat(CONCAT('{\"id\":\"',id,'\",\"name\":\"',name,'\"}') ) as subrow"))
->where('tasks_status', '<>', "Sent Tasks")
->whereNull('user_id')
->orderBy('id', 'desc')
->groupBy('tasks_status')
->get()->map(function ($e) {
$e->subrow = json_decode($e->subrow);
return $e;
});

Is there any complete sample for RadDataForm?

I'm considering using NativeScript-Vue v7.0 for production use and looking into its validation features of data form.
I suppose RadDataForm would be an appropriate component for customizing validation rules, but the documentation following is for NativeScript v6.0, and the source code displayed is corrupted.
https://docs.nativescript.org/vuejs/ns-ui/dataform/dataform-validation
Is there any complete sample code that implements regex-based validation rules and customized error messages?
Documentation (v7): RadDataForm Getting Started
The sample code in the link you provided (updated) is also available on GitHub:
https://github.com/ProgressNS/nativescript-ui-samples-vue/blob/master/dataform/app/examples/Validation.ts
email property with RegEx validator from the link above
Complete example:
import { Frame } from 'tns-core-modules/ui/frame';
import { RegisteringUser } from '../data';
const description = 'Validation';
export default {
name: 'Validation',
description: description,
template: `
<Page>
<ActionBar :title="title">
<NavigationButton text="Back" android.systemIcon="ic_menu_back" #tap="onNavigationButtonTap"></NavigationButton>
</ActionBar>
<StackLayout>
<RadDataForm
ref="dataform"
:source="person"
:metadata="personMetadata">
</RadDataForm>
<Label :text="text"
textWrap="true"
margin="12"
android:color="#C73339"
ios:color="red"
horizontalAlignment="center"></Label>
<Button
text="Login"
margin="12"
horizontalAlignment="stretch"
#tap="onTap()"></Button>
</StackLayout>
</Page>
`,
data () {
return {
title: description,
person: new RegisteringUser(),
text: null,
personMetadata: {
'isReadOnly': false,
'commitMode': 'Immediate',
'validationMode': 'OnLostFocus',
'propertyAnnotations':
[
{
'name': 'username',
'displayName': 'Nick',
'index': 0,
'validators': [
{ 'name': 'NonEmpty' },
{ 'name': 'MaximumLength', 'params': { 'length': 10 } }
]
},
{
'name': 'email',
'displayName': 'E-Mail',
'index': 1,
'editor': 'Email',
'validators': [{
'name': 'RegEx',
'params': {
'regEx': '^[a-zA-Z0-9\\+\\.\\_\\%\\-\\+]{1,256}\\#telerik.com$',
'errorMessage': 'Please provide your #telerik.com email.'
}
}]
},
{
'name': 'password',
'displayName': 'Password',
'editor': 'Password',
'index': 2,
'validators': [
{
'name': 'NonEmpty',
},
{
'name': 'MinimumLength',
'params': {
'length': 6
}
},
]
},
{
'name': 'password2',
'displayName': 'Repeat Password',
'editor': 'Password',
'index': 3,
'validators': [
{
'name': 'NonEmpty',
},
{
'name': 'MinimumLength',
'params': {
'length': 6
}
},
]
},
{
'name': 'age',
'displayName': 'Age',
'index': 4,
'validators': [
{
'name': 'RangeValidator',
'params': {
'minimum': 1,
'maximum': 100,
'errorMessage': 'Age must be between 1-100.',
}
},
],
},
{
'name': 'agreeTerms',
'displayName': 'Agree Terms',
'index': 5,
'validators': [
{
'name': 'IsTrueValidator',
},
],
}
]
}
};
},
methods: {
onNavigationButtonTap() {
Frame.topmost().goBack();
},
onTap() {
let isValid = true;
const pName = this.$refs.dataform.getPropertyByName('username');
const pPwd = this.$refs.dataform.getPropertyByName('password');
const pPwd2 = this.$refs.dataform.getPropertyByName('password2');
if (pName.valueCandidate.toLowerCase() !== 'admin1') {
pName.errorMessage = 'Use admin1 as username.';
this.$refs.dataform.notifyValidated('username', false);
isValid = false;
} else {
this.$refs.dataform.notifyValidated('username', true);
}
if (!pPwd.valueCandidate) {
pPwd.errorMessage = 'Password is empty.';
this.$refs.dataform.notifyValidated('password', false);
isValid = false;
}
if (pPwd2.valueCandidate !== pPwd.valueCandidate) {
pPwd2.errorMessage = 'Password is not the same as above.';
this.$refs.dataform.notifyValidated('password2', false);
isValid = false;
} else {
this.$refs.dataform.notifyValidated('password2', true);
}
if (!isValid) {
this.text = 'Username or Password is not valid.';
} else {
this.text = '';
this.$refs.dataform.commitAll();
alert({
title: 'Successful Login',
message: `Welcome, ${this.person.username}`,
okButtonText: 'OK',
});
}
}
}
};

Graphql Cannot create property 'clientMutationId' error on mutation?

this is the mutation I want to perform:
const GraphQLAddPlayerResponseMutation = mutationWithClientMutationId({
name: 'AddPlayerResponse',
inputFields: {
cdx: { type: new GraphQLNonNull(GraphQLInt) },
},
mutateAndGetPayload: ({cdx}) => {
var cdxAdded = addplayerResponse(cdx);
console.log("cdxAdded = ",cdxAdded)
return cdxAdded;
}, // what u return on mutateAndGetPayload is available on outputFields
outputFields: {
playerResponse: {
type: GraphQLInt,
resolve: ({cdxAdded}) => {
console.log("outputFields cdxAdded = ",cdxAdded)
return cdxAdded
},
},
viewer: {
type: GraphQLUser,
resolve: () => getViewer(),
},
},
});
Can't figure out what's wrong with the code, it logs on the mutateAndPayload:
mutateAndGetPayload: ({cdx}) => {
var cdxAdded = addplayerResponse(cdx);
console.log("cdxAdded = ",cdxAdded)
return cdxAdded;
},
but I think the outputFields is not evaluated since it's not logging in the console and I get this error:
{
"data": {
"addPlayerResponse": null
},
"errors": [
{
"message": "Cannot create property 'clientMutationId' on number '3'",
"locations": [
{
"line": 4,
"column": 3
}
],
"path": [
"addPlayerResponse"
]
}
]
}
Help?
Replace return cdxAdded; by return { cdxAdded }; (wild guess)

Resources