Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PhilKz's avatar

Unable to Access Eager-Loaded Property from Inside Reactjs Return

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.)

0 likes
1 reply
PhilKz's avatar
PhilKz
OP
Best Answer
Level 9

OK, I figured this out now. The problem was that there was not a program_question relationship for every question, so in some cases "...program[0]" didn't exist. The two possible solutions are:

  1. Guarantee that at least one program_question relationship must exist for every question as part of the back end.

  2. Map over the programs object, so that if programs is empty it doesn't do anything. This has the advantage of not blowing up if 1 fails.

<p>Programs: {question.programs.map(program => program.name)}</p>

Please or to participate in this conversation.