Vue - InertiaJS: Enter Object not able - javascript

In my props, I pass the array "ticket_data" when loading the Vue component. Now I want to make a post to a controller using the Inertia form. This also works without problems.
My problem is, I can not access individual values from the array ...
My code:
let props = defineProps({
ticket_data: Object,
ticket_messages: Object,
});
let form = useForm({
text: '',
});
let submit = () => {
form
.transform((data) => ({
data,
ticket_id: props.ticket_data.ticket_id, // null
ticket_id: props.ticket_data, // gives all Data see Json
}))
.post('/account/user/support/ticket/send', {
preserveScroll: true,
onSuccess: () => form.reset('text'),
});
};
If I submit props.ticket_data individually, the following post arrives at my controller:
"ticket_id":[{"user_id":1,"ticket_id":5,"reference":"Testticket","state":0,"author":"Kevin Johnson","text":"..","created_at":"11/04/22 - 19:58"}]}
If the data arrives with "props.ticket_data", why can't I just access it with "props.ticket_data.ticket_id" ?
"props.ticket_data.[1]" doesn't work like that either....

Get a ticket by Id like this:
props.ticket_data.find(ticket => ticket.ticket_id === 5) // <-- ticket id

Related

Pushing to an array is returning index rather then items (React)

I'm trying to add a new object to the end of an array that I'm dynamically fetching over my API. Users complete a form so the data is passed from the form to the state.
The initial first fetch is storing the original array to some react state which is fine, then at some point, a single object should be added to the end of the original array, so the whole array will contain the original data, plus the new object added.
Naturally, I'm trying to use array.push() to try and achieve this, but I keep getting the index rather than the data object.
// declare state will be an array
const [originalPages, setOriginalPages] = useState([]);
// Get all the existing data
loadInitialValues() {
return fetch(`example.com/api/collections/get/testing_features?token=${process.env.REACT_APP_API_KEY}`)
.then((res) => {
return res.json();
})
.then((res)=>{
// set state to be the whole array for this post
setOriginalPages(res.entries[4].pagebuild);
return res.entries[4].pagebuild[0].settings;
})
.catch((err)=>{
console.error(err);
})
}
At this point the data is all working completely fine, the collection of the new data from the forms works fine too. However, this is the point when the data goes to get posted back to update the API but just returns a number:
onSubmit(formData) {
// Dynamically hook all the newly collected form data to this new data object
let theData = {
component: 'page',
settings: {
title: formData.title,
pageOptions: {
pageSideImg: formData.pageOptions.pageSideImg,
isReversed: formData.pageOptions.isReversed,
paraGap: formData.pageOptions.paraGap,
paraFont: formData.pageOptions.paraFont,
},
pageNavigation: {
pageSlug: formData.pageNavigation.pageSlug,
nextPage: formData.pageNavigation.nextPage,
prevPage: formData.pageNavigation.prevPage,
},
globalOptions: {
projectName: formData.globalOptions.projectName,
transType: formData.globalOptions.transType,
menuTrans: formData.globalOptions.menuTrans,
},
blocks: formData.blocks
}
};
cms.alerts.info('Saving Content...');
return fetch(`example.com/api/collections/save/testing_features?token=${process.env.REACT_APP_API_KEY}`, {
method: 'post',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
data: {
// Only returning the array count as a number
pagebuild: originalPages.push(theData),
_id: "610963c235316625d1000023"
}
})
})
.then(response => response.json())
.catch((err) => {
cms.alerts.error('Error Saving Content');
console.log(err);
});
},
If anyone has any ideas as to why this is happening id greatly appreciate it!
For reference, I've checked here and maybe I should use spread instead?
The Array.push doesn't return the final array you would need, but the final length of modified array (that's why you thought it was an index).
Replace this string pagebuild: originalPages.push(theData), with this one:
pagebuild: [...originalPages, theData],
Of course, if you want to update the internal originalPages state value, call this within your onSubmit():
setOriginalPages(x => [...x, theData]);

Object items are not rendering (Object is stored in an array of objects which in turn is stored in a React state hook)

My problem is that item stored in object (in an array of objects inside a state hook) is not being rendered on page, but it gets printed with console.log
I fetched some data from the server and it worked as expected, returning an array of two items, one of which is an object containing blog data(blog heading, creator, etc) an another is an array of 'sections' of that blog. Here is how I did it,
This is the initialization
// Get the blog id
const {blog_id} = useParams();
// Declaring our state hooks
const initial_blog_state = {
blog_id: blog_id,
heading: '',
creator: {},
created: '',
section: [],
}
const [blog_state, updateBlogState] = useState(initial_blog_state);
Here is the fetching of data from the server
useEffect(() => {
// Fetching data
Promise.all([
fetch(`http://127.0.0.1:8000/api/blog/${blog_id}`),
fetch(`http://127.0.0.1:8000/api/section/full/${blog_id}`)
]).then(responses => {
// Get a JSON object from each of the responses
return Promise.all(responses.map(response => {
return response.json()
}))
}).then(function (data) {
// Log the data to the console
console.log(data);
// Update state
updateBlogState({
...blog_state,
heading: data[0].heading,
creator: data[0].creator,
created: data[0].created,
section: data[1]
})
}).catch(function (error) {
// if there's an error, log it
console.log(error);
});
}, []);
I think the way I'm updating the section inside the hook can be a problem(although I'm not sure how), because I saw in a stackoverflow answer that objects must always be initialized (which I'm not doing when declaring an array of 'objects')
And here is the thing that needs to be rendered
return (
<div className="container">
<h1>{blog_state.heading}</h1>
<p className="text-small text-muted">{blog_state.creator.username}</p>
{blog_state.section.map(item => {
{console.log(item.paragraph)}
<p>{item.paragraph}</p>
})}
</div>
)
Here blog_state.heaing and blog_state.creator.username are being rendered as desired and also console.log(item.paragraph) prints the correct paragraph on the console window, but item.paragraph doesn't show anything on the page.
Nothing is being returned from your map.
i.e you need to add a return line before the <p>{item.paragraph}</p>
So:
{blog_state.section.map(item => {
console.log(item.paragraph)
return <p>{item.paragraph}</p>
})}
or as an inline return:
{blog_state.section.map(item => <p>{item.paragraph}</p>)}

How to remove attributes from angular ReactiveForm without changing the original one?

I have an angular reactive form made by form array like below and store it on myForm variable.
this.myForm= this.fb.group({
elements: this.fb.array(
this.formElements.map((e, i) => {
return this.fb.group({
Active:e.Active,
Id:e.Id,
Name:e.Name
})
})
),
})
After I edit this form,I need to send it to API but there is name attribute which is not necessary therefore should be removed from params object.
save()
{
const formValue=[...this.myForm.value.elements];
formValue.forEach(e=>{delete e.Name;});
const params={"dataObject":formValue}
}
Not to change original form I decided to make hardcopy of formValue but didnt change anything.How can I keep original form and send it to API with removed name attributes?
EDIT
While trying different methods this one solved the problem.
const formValue=JSON.parse(JSON.stringify(this.myForm.value.elements));
Is there another better way instead of JSON stringifying and parsing?
You can use Array.prototype.map.
const params = {
"dataObject": formValue.map(({ Name, ...e }) => ({ ...e }));
}

Show length of data array in VueJS after getting the data from API

I'm using Vue JS to get some data from an API. I want to get the length of this array and log to console via a method.
But it always logs the value of "0" instead of the real length.
I can access the data in the html without any problem and show the length ( {{ termine.length }} ).
But I want to do it using the method "logToConsole".
It seems to be a problem to access the data (which seems to be undefined in the moment of function call).
I fetch the data on "created", and output the length in "mounted", so it should be available (?).
Do you have any idea why I cannot access the data of the array in my "mounted" function, even after getting the data in "created"?
new Vue ({
el: "#calendar",
data: {
termine: [],
},
},
created() {
fetch("https://www.myurl.com/data/?json&function=GetEvents")
.then(response => response.json())
.then((data) => {
this.termine = data;
})
},
mounted() {
this.logToConsole();
},
methods: {
logToConsole: function () {
console.log(this.termine.length);
},
},
})
Of course, created hook is triggered before mounted.
But you know, you are setting termine property using API response and it is happen with async.
If you simple set termine property with simple statement like this.termine = ['a', 'b'], it will logs 2.
If you want log the data after getting the value using API, you could use watch.
like:
watch: {
termine(val) {
console.log(val)
}
}

How to save the objects uid when I push the data in firebase database list, using javascript

I want to save the uid when I push new data in Firebase database. This is possible not for auth users but for data objects.
For example, I want this object schema:
"-Kdsfdsg555555fdsgfsdgfs" : { <------- I want this id
Id : "Kdsfdsg555555fdsgfsdgfs", <--- How to put that inside
name : "A",
time_updated : "6/6/2017"
}
Is any way how to get this id and pushed inside the object?
My code is as follows:
categories: FirebaseListObservable<any[]>;
this.categories = this.db.list('/categories') as FirebaseListObservable<Category[]>;
addCategory(category: any) {
return this.categories.push(category).then( snap => {
this.openSnackBar('New category has been added', 'ok');
}).catch(error => {
this.openSnackBar(error.message, 'ok');
});
}
There are two ways to use Firebase's push() method:
By passing in an argument, it will generate a new location and store the argument there.
By passing in no arguments, it will just generate a new location.
You can use the second way of using push() to just get the new location or its key:
addCategory(category: any) {
var newRef = this.categories.push();
category.Id = newRef.key;
newRef.set(category).then( snap => {
this.openSnackBar('New category has been added', 'ok');
}).catch(error => {
this.openSnackBar(error.message, 'ok');
});
}
But note that it's typically an anti-pattern to store the key of an item inside that item itself too.

Categories

Resources