Home > database >  Cannot fetch JSON data using GET method: resJSON is not defined error
Cannot fetch JSON data using GET method: resJSON is not defined error

Time:02-12

I'm trying to get data from backend server usin this fetch function:

 let users = []
  const fetchUsers = () => {
    fetch(baseUrl   "/users/", {
      method: "GET",
    })
      .then((res) => res.json())
      .then((data) => (resJSON = data))
      .then((resJSON) => {
          users = resJSON;
      })
      .catch((err) => {
        console.log("error in json", err);
        users = [];

      });
  };

But I get

error in json ReferenceError: resJSON is not defined

error happens in this line: .then((data) => (resJSON = data))

The wierd thing is that I see in the backend that the json is created. Also I'm using very similar fetch request for POST data on another endpoint without any issues. So I'm wondering what could be wrong here?

CodePudding user response:

The problem is that resJSON = data is assigning to an identifier that isn't declared anywhere. Apparently your code is running in strict mode (good!), so assigning to an undeclared identifier is an error.

But there's no need for resJSON, it doesn't do anything useful in that code. You could combine the two then handlers and do users = data. But, that's generally poor practice, because you're setting yourself up for this problem where you try to use users before it's filled in. (Your code is also falling prey to the fetch API footgun I describe in this post on my anemic old blog: You need to check ok before you call json().)

But fundamentally, having fetchUsers directly assign to a users variable declared outside of it is asking for trouble. Instead, have fetchUsers return a promise of the users array. Here in 2022 you can do that with an async function:

const fetchUsers = async () => {
    const response = await fetch(baseUrl   "/users/", {
        method: "GET",
    });
    if (!response.ok) {
        throw new Error(`HTTP error ${response.status}`);
    }
    return await response.json();
};

(If you want to hide errors from the calling code (which is poor practice), wrap it in a try/catch and return an empty array from the catch.)

Then have the code that needs to fill in users do let users = await fetchUser(); (note that that code will also need to be in a async function, or at the top level of a module).

If for some reason you can't use an async function, you can do it the old way:

const fetchUsers = () => {
    return fetch(baseUrl   "/users/", {
        method: "GET",
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error ${response.status}`);
        }
        return response.json();
    });
};

CodePudding user response:

You are having an assignment in your return statement. Additionally, this assignment is scoped to the current callback, so in the next .then block resJSON is not available. It is also not required to try to do an extra assignment.

let users = []
fetch(/* ... */)
   .then((res) => {
        // res is the raw response.
        // res.json returns a new promise
        // that when sucefully fulfilled, 
        // will return the decoded body
        return res.json()
    })
   .then((data) => {
     // data refers to the json decoded 
     // bytes of the response body
     // assign it directly to user
     users = data
   })
   .catch(console.warn)

This may be still problematic, as you never know when the users are assigned or not. Depending on your code, you should shift additional work to the callback itself.

const useUserdata = (users) => 
    console.log("do something with the user", users)

fetch(/* ... */)
   .then((res) => res.json())
   .then(useUserdata)
   .catch(console.warn)
  • Related