Home > Software design >  How to add conditionals to an await fetch request?
How to add conditionals to an await fetch request?

Time:04-22

I'm working with an API in Next.js and I'm trying to make a back/next button functional. With my code though, I'm getting a "res is not defined". How do I properly use conditionals with an await fetch request?

const Page = () => {
  const [page, setPage] = useState(1);
  const [data, setData] = useState(null);

  const fetchContent = async (button) => {
    if (button === "back" && page > 1) {
      const res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
      setPage(page - 1);
    } else if (button === "next") {
      const res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
      setPage(page   1);
    } else {
      const res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
    }
    const data = await res.json();
    setData(data.data);
  };

  useEffect(() => {
    fetchContent();
  }, []);

  return (
    <div>
      <button
        onClick={() => {
          fetchContent("back");
        }}
      >
        Prev page
      </button>
      <button
        onClick={() => {
          fetchContent("next");
        }}
      >
        Next page
      </button>
  );
};

export default Page;

CodePudding user response:

Your conditionals look fine. The problem is const (and let) being block-scoped: they disappear as soon as the block they were defined in ends. Here is your situation, simplified:

{
  const a = 1;
  console.log("inside a block", a);   // 1
}
console.log("outside a block", a);    // ReferenceError

The solution: make res not a constant, and declare it at the scope you will use it:

let a;
{
  a = 1;
  console.log("inside a block", a);   // 1
}
console.log("outside a block", a);    // 1

CodePudding user response:

declaring const variables inside of code blocks, you can't reach from outside blocks.

you have to pull that res out of the block.

and it should work

const fetchContent = async (button) => {

    let res; // out of the block

    if (button === "back" && page > 1) {
      res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
      setPage(page - 1);
    } else if (button === "next") {
      res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
      setPage(page   1);
    } else {
      res = await fetch(
        `http://api-page.com/content/pagination[page]=${page}`
      );
    }
    const data = await res.json();
    setData(data.data);
  };
  • Related