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?
>Solution :
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();
});
};