MrDave1199's avatar

Need Help with a refresh on a modal that fetch data from a db to table

I'm developing a tag adder for my classify system, it's loaded on a modal which contains 4 subtags with the same function

But I'm unable to add a new tag (theme in this example) and at the same time reload a modal (not the full page) reseting the input field and viewing the new entry in the table

It's my first project using laravel livewire and i'm really stuck in this...i know i could do it easily without modals but client asked to keep it in this way as it's easier for them than loading different routes

<?php
use App\Models\tema;
use Livewire\Volt\Component;

new class extends Component
{
    public $sorted_temas;
    public string $temaName = '';

    public function mount($temas): void
    {
        $this->sorted_temas = $temas;
    }

    public function createTema()
    {
        $validated = $this->validate([
            'temaName' => ['required', 'string', 'max:255'],
        ]);

        $registro = new tema;
        $registro->tema_name = $validated['temaName'];
        $registro->save();
    }
}
?>


<div class="hidden p-1 rounded-lg bg-none" id="profile" role="tabpanel" aria-labelledby="profile-tab">
    <table class="text-sm text-left text-gray-500 dark:text-gray-400" style="width: 100%">
        <tbody>
            @foreach($sorted_temas as $key => $tema)
            <tr class="bg-white border-b dark:bg-gray-800 dark:border-gray-700">
                <td class="block w-full p-4 pl-10 text-sm text-gray-900  rounded-lg bg-gray-50">{{$tema->tema_name}}</td>
            </tr>
            @endforeach
            <tr>
                <td class="block w-full p-4 pl-10 text-sm text-gray-900 bg-gray-50">
                    <form wire:submit="createTema" method="POST">
                    @csrf
                        <div class="flex" style="justify-content: flex-end; align-items: center">
                            <input wire:model="temaName" type="text" id="temaName" name="temaName" class="block w-full text-sm text-gray-900 border-none rounded-lg bg-gray-50 focus:outline-none focus:ring-0" placeholder="{{__('messages.newTem')}}" style="padding: 0.1em 0;" required>
                            <button type="submit" class="text-white relative right-2.5 bottom-2.5 bg-gray-500 hover:bg-gray-50 hover:text-gray-500 focus:outline-none focus:ring-0 font-medium rounded-lg text-sm px-4 py-2 ">{{__('messages.manBut')}}</button>
                        </div>
                    </form>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Undefined variables comes from the container which is technically the modal but it loads the tags into tabs in this div

<div id="default-tab-content" style="max-height: 20em; overflow-y: scroll">
            <livewire:pages.fun.tagBlades.tema :temas="$sorted_temas"/>
            <livewire:pages.fun.tagBlades.subtema :subtemas="$sorted_subtemas"/>
            <livewire:pages.fun.tagBlades.sector :sectores="$sorted_sectores"/>
            <livewire:pages.fun.tagBlades.profesional :profesionales="$sorted_profesionales"/>
            <livewire:pages.fun.tagBlades.origen :origenes="$sorted_origenes"/>
        </div>
0 likes
4 replies
alden8's avatar

In Laravel Livewire, you can use the 'render' method to refresh the component view. After saving the new 'tema', you can reset the 'temaName' property and call the 'render' method to refresh the view.

Here's how you can modify your createTema method:

public function createTema()
{
    $validated = $this->validate([
        'temaName' => ['required', 'string', 'max:255'],
    ]);

    $registro = new tema;
    $registro->tema_name = $validated['temaName'];
    $registro->save();

    // Reset the input field
    $this->temaName = '';

    // Refresh the sorted_temas
    $this->sorted_temas = tema::all();

    // Refresh the component view
    $this->render();
}

In the above code, after saving the new 'tema', we reset the 'temaName' property to an empty string. Then we refresh the 'sorted_temas' property by fetching all 'tema' from the database again. Finally, we call the 'render' method to refresh the component view.

This will clear the input field and show the new 'tema' in the table without reloading the whole page.

Also, make sure to remove the 'method="POST"' and '@csrf' from your form. Livewire handles these automatically.

1 like
MrDave1199's avatar

@alden8

This is how it is seen before the adding

dpm1999.com/Resources/Pictures//ss.png

But then if i add a new theme the table empties

dpm1999.com/Resources/Pictures//ss_after.png

If i change tab and return it is good again but is something a client would never accept

Also thanks, i didn't knew livewire handles the forms method and security by his own

1 like
alden8's avatar

@MrDave1199 Hey mate. I'm dlad resolve you problem. If my tips help you fix your problems, choose one of my tips as the best tip in this topic. Here are some more tips to fix your trouble and improve.

Data Synchronization: -- Ensure the sorted_temas property is synchronized across related components. -- If other components access this data, make them reactive using $refresh or events. -- Consider using a shared parent component or broadcasting events to maintain consistency.

Component Rendering:

- Reassess the component structure and rendering logic.
- Verify that the sorted_temas property is properly passed to the table component.
- Check for any JavaScript errors or conflicts that might interfere with rendering.

Life Cycle Hooks:

- Utilize Livewire's life cycle hooks to update data at appropriate stages.
- Use the mount hook to fetch initial data and the updated hook to handle changes.

Code Optimization:

- Remove unnecessary method="POST" and @csrf from the form.
- Consider using Alpine.js for more granular reactive updates within the modal.

Debugging and Testing:

- Use Livewire's $this->emitSelf('update') for explicit re-rendering.
- Inspect network requests and Livewire logs in the browser console.
- Isolate the issue by testing components individually.

Additional Considerations:

- Modal Implementation: If using a custom modal solution, ensure it integrates seamlessly with Livewire's reactivity.
- Data Fetching: Optimize data fetching methods for efficiency, especially when dealing with large datasets.

Tailored Guidance. To provide more specific guidance, please share:

- Relevant code snippets for the modal component, table component, and any other involved components.
- JavaScript code related to modal behavior and tab switching.
- Livewire and Laravel versions you're using.

Please or to participate in this conversation.