State Management · Junior · Question 67 of 75

Why should an SWR fetcher throw on non-OK HTTP responses?

const fetcher = async (url) => {
  const res = await fetch(url);
  if (!res.ok) throw new Error("Request failed");
  return res.json();
};

Explanation

A thrown error is exposed as error and enables SWR's retry logic. You can attach status and the response body to the error for the UI.

Further reading

Problem with a question

State Management · Junior · question 67

Test yourself

Take the State Management · Junior quiz: questions and options are shuffled, and you get a review of your mistakes at the end.

Take this quiz