My Inertia + React app has a Question model and a Program model with a many to many relationship between them. I am trying to write a view that lists all available questions and, within each question, lists which programs each question is part of.
However, for some reason, I cannot access the programs property inside of my return statement, even though I can access it elsewhere in the jsx file. I would appreciate it if anyone could explain why and how to fix this.
This is my controller logic:
$questions = Question::with('programs')->get();
return inertia('ListOfQuestions',['questions' => $questions]);
In my jsx file, I can correctly access the name of a program before the return statement, like so:
function ListOfQuestions(){
const questions = usePage().props.questions;
//Outputs 'n3'.
console.log(questions[0].programs[0].name);
However, inside the return statement, I cannot access the same property using:
{questions.map((question,i)=>{
return <div key={question.id} className='py-4'>
<p>Question Id {question.id}.</p>
<p>Programs: {question.programs[0].name}</p>
//Other properties...
</div>
})}
All of the non-eager-loaded properties (i.e. all properties except 'programs') work as expected ({questions.id} works fine).
The error that this throws is "Uncaught TypeError: question.program is undefined."
Edit: fixed a typo in the code example (the typo was not the problem in the code, I just made a mistake when copying it.)