Reputation: 1
I'm using Inertia with Vue3. I did not understand clearly the responses. If someone make this example clear for me, I believe I'll understand the logic. Sorry if it's a silly question.
I have a simple post form: title description
and also a "tags" section; which user can use the existed tags, or they can create a new tag and here it is the problem.
When I submit a new tag, I want to retrieve the data and push it into the tags props on the onSuccess state and keep the title and description sections. But I do not know how to deal with it, I can not return any json data on my server side, even if I can, I do not want to send a json data manually, if I have to use ajax or xhr request manually what is the point of using Inertia.Thanks.
I want to retrieve the inserted data on the onSucess state. I checked it out the inertia docs but did not get it.
Passing the data from the controller:
defineProps({
tags: {
type: Array,
required: true
},
styles: {
type: Array,
required: true
},
})
const tags = ref(page.props.tags);
const styles = ref(page.props.styles);
let addTag = () => {
tagForm.post('/tags', {
preserveScroll: true,
resetOnSuccess: false,
onSuccess: () => do_the_job_here, //push the inserted tag into the tags
})
};
Server Side:
$data = $request->validate([
'name' => 'required|string|max:255',
]);
$tag = Tag::create($data);
//pass the $tag here
Upvotes: 0
Views: 1499
Reputation: 389
Just use tagForm, You can handle it on front side.
> let addTag = () => {
> tagForm.post('/tags', {
> preserveScroll: true,
> resetOnSuccess: false,
> onSuccess: () => this.tagForm // you can access form here as well user input >Tag .
> }) };
Upvotes: 0
Reputation: 146
Unfortunately, there's no direct way. It can be done in this hacky way, though.
Change your App\Http\Middleware\HandleInertiaRequests
middleware to have a data key in Shared data
public function share(Request $request): array
{
return array_merge(parent::share($request), [
'auth.user' => \Auth::user(),
'flash' => [
'error' => fn () => $request->session()->get('error'),
'success' => fn () => $request->session()->get('success'),
'data' => fn () => $request->session()->get('data') // add this line
],
]);
}
While processing your request on the server side, you can do something like this:
public function submitTagForm()
{
// process form data
return redirect()->back()
->with('success', 'Settings saved successfully')
->with('data', ["one"=> "one", "two"=> "two"]); // add this extra line to pass desired data
}
Finally, in your Inertia.Js code, you can simply access any data passed:
addTag.post('tags', {
preserveScroll: true,
resetOnSuccess: false,
onSuccess: (response) => {
console.log(response.props.flash.data);
}
})
Upvotes: 0