I have a laravel ap and I am trying to fetch some data from an external api and display this data with React.
There is a search field with a submit button and under this form a list of the results. When I press the search button the data gets fetched successfully from the external api but in my front end I can’t display the results my component stays empty. I think I’ve setup the routes wrong maybe? I think the issue is it tries to redirect to ‘/’ and that empties the results everytime ? Something is not correct there I think.
In my console I get this error after submitting:
Uncaught (in promise) TypeError: this.resolveComponent is not a function
My Kernel.php
class Kernel extends HttpKernel
{
/**
* The application's route middleware groups.
*
* @var array<string, array<int, class-string|string>>
*/
protected $middlewareGroups = [
'web' => [
AppHttpMiddlewareHandleInertiaRequests::class,
],
];
}
Routes in web.php
Route::controller(LegoController::class)->group(function () {
Route::get('/','index')->name('lego.index');
Route::get('/searchParts','searchParts')->name('lego.searchParts');
});
LegoController.php
class LegoController extends Controller
{
public function __construct(private LegoProvider $legoProvider)
{
}
public function index()
{
return Inertia::render('Index');
}
public function searchParts(Request $request): Response
{
if (!$request->setNumber) {
return Inertia::render('PartsList', ['parts' => Collection::make()]);
}
return Inertia::render('PartsList', ['parts' => $this->legoProvider->getPartsBySet($request->setNumber)]);
}
}
Index.jsx
import React, { useState } from 'react';
import { router } from '@inertiajs/react'
import PartsList from "./PartsList.jsx";
const Index = () => {
const [values, setValues] = useState({
setNumber: "",
});
function handleChange(e) {
const key = e.target.id;
const value = e.target.value
setValues(values => ({
...values,
[key]: value,
}))
}
function handleSubmit(e) {
e.preventDefault()
router.get('/searchParts', values)
}
return (
<>
<h1>Search parts by set number</h1>
<hr/>
<form onSubmit={handleSubmit}>
<label htmlFor="setNumber">Set Number:</label>
<input id="setNumber" value={values.setNumber} onChange={handleChange} />
<button type="submit">Search</button>
</form>
<PartsList />
</>
)
}
export default Index
PartsList.jsx
import React, { useState } from 'react';
const PartsList = ({ parts }) => {
return (
<>
<h1>Parts</h1>
<hr/>
{ parts && parts.map( (part) => (
<div key={part.id}>
<h2>{part.partName}</h2>
<a href={part.partUrl}>{part.partNumber}</a>
</div>
)) }
</>
)
}
export default PartsList