Fetch returns null but after page refresh returns object. How to fix it?

I have an array of 500 posts id. I need to get an array of the first 100 posts. So I do the following:

API
https://github.com/HackerNews/API
BASE_URL = 'https://hacker-news.firebaseio.com/v0'

    const checkResponse = (response: Response) => {
      return response.ok ? response.json() : Promise.reject(`Some error`);
    };
    
    const fetchStoryIdList = async (): Promise<any> => {
      try {
        const response = await fetch(`${BASE_URL}/newstories.json`);
        const idJson: number[] = await checkResponse(response);
        return idJson;
      } catch (error) {
        console.log(error);
      }
    };
    
        const fetchStoryList = async () => {
          const idList = await fetchStoryIdList(); // idList is an array of 500 ids
        
          const promises: IStory[] = idList.slice(0, 100).map(async (id: number) => {
            try {
              const response = await fetch(`${BASE_URL}/item/${id}.json`);
              const storyData: IStory = await checkResponse(response);
              return storyData;
            } catch (err) {
              console.log(err);
            }
          });
        
          const storyList = await Promise.all(promises);
          console.log('storyList:', storyList);
        
          return storyList;
        };

Problem

Sometimes API call for a single post data returns null. So I get an array of posts and null. Then its renders in component and crashes because of null. After app crashes I manually refresh page and API calls fire again but this time everyting is fine.

For exapmple fetch request for post with id 28359987 returns null but after I refresh page new Api call returns post for the same id…after a while a get null again for another id…then refresh page and null is gone. How to fix that?

enter image description here

Answer

You might have had an api error where it fails for a certain request. Although as can be seen in this codesandbox example – it’s always working https://codesandbox.io/s/crazy-knuth-dbldy?file=/src/App.tsx

As for removing the null value you can append .filter(Boolean) since the null results are useless to you

// don't forget those () around await
const storyList = (await Promise.all(promises)).filter(Boolean)