Javascript unable to iterate over an array

I have an array, and instead of iterating over it, the browser says that data.map() is not a function. All of the answers to this that I found said that this problem comes when the data is not an array, but my data definitely is an array.

Strangely enough, this happens only when fetching data from the url, but when I use a saved .json file of the fetched data, the program works just fine. I don’t think I have done anything wrong in my fetching of the data – I get data like so –

export default function useFetch(url) {
  const [state, setState] = useState({
    data: "",
    loading: true,
  });

  useEffect(() => {
    setState((state) => ({
      data: state.data,
      loading: true,
    }));

    fetch(url)
      .then((x) => {
        if (x.ok) {
          return x.json();
        }
      })
      .then((y) => {
        setState({
          data: y,
          loading: false,
        });
      });
  }, [url, setState]);

  return state;
}

In the other component I give a constant a value :

const { data, loading } = useFetch(url);

And then it will crash my program, saying that it data.map() is not a function

However, when I manually go to the same url, and save the JSON file that is there, and then use the file instead of fetch, the program works just fine. const data1 = require("../data.json");

So I have a case, where data.json that is exactly the same as data that I get from fetch request works, while the fetch request itself doesnt. Not only that, but I am also able to do a console log for things like data[0].name and other things like that.

And the last problem is, that this morning, the program was also working with the fetch version itself, I simply saved the .json files and started using them instead, because I didn’t want to keep sending requests to the server. And at some point I wanted to start testing it with actual feth responses, and then it didn’t work anymore.

As a final bit of information – When I compile the program with the saved .json file, and then change the code to use the fetched data and save, then my program will not crash, and I can use the same and also other fetched data until I refresh the browser, at which point I get the error again.

Answer

consider initializing state as

{
    data: [],
    loading: true,
  }

Leave a Reply

Your email address will not be published. Required fields are marked *