score:3

Accepted answer

The generateQuestion callback is asynchronous, so you won't be able to send data in route state via the Link, but what you can do is move the onClick handler to the Link and call event.preventDefault on the click event to prevent the navigation action, and issue an imperative navigation after the questions have been fetched.

Example:

import { Link, useNavigate } = 'react-router-dom';

...

const navigate = useNavigate();

...

generateQuestions = async (event) => {
  event.preventDefault();

  try {
    const data = await questionsData();
    const arrData = data.map(element => ({
      ...element,
      id: nanoid(),
    }));

    navigate("/quiz", { state: { questions: arrData } });
  } catch(error) {
    // handle rejected Promise/error/etc...
  }
}

...

<Link to="/quiz" onClick={generateQuestions}>
  <button type="button">
    Start Quiz
  </button>
</Link>
...

In the Quiz component use the useLocation hook to access the passed route state.

import { useLocation } from 'react-router-dom';

...

const { state } = useLocation();
const { questions } = state || {};

Related Query

More Query from same tag