Do you pass your person as a prop to your modal component? Can you post more code of your React components (component that displays the modal + the modal component)?
Show many-to-many in table - Inertia with React
I have a query in my index() method that searches a datatable:
use Inertia\Response as InertiaResponse;
public function (Request $request) : InertiaResponse
{
$search = $request->query('search');
//* Allow admin access
if(Gate::allows('is-admin')) return Inertia::render('Admin/Users/Index', [
'users' => User::query()->when($search, fn ($query) =>
$query->where('name', 'LIKE', "%{$search}%")->orWhere('email', 'LIKE', "%{$search}%")
)->with('roles')->orderByDesc('created_at')->paginate(10)->withQueryString(),
]);
}
In my frontend, I have a show button that has an onClick() listener that sets the state of a particular record:
<button onClick={(e) => {
setPerson({roles: [user.roles]});
setShowData(true); /* sets the state of the modal to true */
console.log(Object.values(user.roles));
}}
>
Show
</button>
This is what I get in the console:
[
0: {id: 1, role: 'Admin', created_at: null, updated_at: null, pivot: {…}}
1: {id: 2, role: 'Designer', created_at: null, updated_at: null, pivot: {…}}
2: {id: 3, role: 'Cashier', created_at: null, updated_at: null, pivot: {…}}
]
length: 3
/* This is a detail of one of the objects */
0:
created_at: null
id: 1
pivot: {user_id: 26, role_id: 1}
role: "Admin"
updated_at: null
which I think is what I should be getting. But when I try to display the values in the modal {person.roles} it doesn't show, and when I try to use {person.roles.role} or use console.log(user.roles.role) it gives me a null with an error showing undefined. How can I display this data?
@piljac1 I actually solved it. I just passed the Object.values() into the setState({roles: []}) array and then mapped them over using state.roles.map() and I output the values. It was not obvious to think about. I don't know if it was the best way but It worked out.
Please or to participate in this conversation.