React Native
Loading questions
Learn to load questions with fetch.
Loading questions
In this lesson you will write a function that loads questions from an API. You define an async function loadQuestions; inside it you put await fetch and await response.json(). This function returns a Promise; when it resolves it gives the questions array.
The questions constant from the previous lesson is a local fallback; in a real app the data comes from the server. But keeping both during development is common: if the API is down, the fallback constant is used. This lesson builds on the previous units where you learned fetch and response.json(). What you do: async function loadQuestions() { const response = await fetch(url); const data = await response.json(); return data; }.
Exercise Write loadQuestions
The questions constant from the previous lesson is already defined below. Now add an async function loadQuestions. Assign await fetch("https://api.example.com/questions") to const response. Assign await response.json() to const data. Return the data with return data.
Show example solution
const questions = [
{ id: 1, question: "Capital of Turkey?", options: ["İstanbul", "Ankara", "İzmir"], answer: 1 },
{ id: 2, question: "What is 2 + 2?", options: ["3", "4", "5"], answer: 1 }
];
async function loadQuestions() {
const response = await fetch("https://api.example.com/questions");
const data = await response.json();
return data;
}
API and fallback data
In real apps the API sometimes fails. So it is common to keep fallback data. When loadQuestions fails, in the catch block you return the fallback questions constant.
This approach keeps the app working in every situation. Instead of showing the user an error, you continue with the fallback data. In the next lessons you will call this function from inside a Quiz component; when the component mounts, the questions are loaded. The loading flow is a core part of data management; on this foundation you will build the quiz flow.
Test yourself
-
Why must loadQuestions be async?
function loadQuestions() { /* ... */ }
- Because it is fast
- Because React requires it
- Because fetch returns a Promise, which must be awaited
- Because it is shorter
Show answer
Because fetch returns a Promise, which must be awaited — fetch returns a Promise; awaiting needs async.
-
Return the loaded data
async function loadQuestions() {
const response = await fetch(url);
const data = await response.json();
____;
}
Show answer
async function loadQuestions() {
const response = await fetch(url);
const data = await response.json();
return data;
}
-
Match the concept to its role
- fetch
- Makes a request
- response.json()
- Parses JSON
- await
- Waits for a Promise
- return data
- Returns the data
Next lesson: Running the quiz