After fetching, null is returned; however, refreshing the page results in the object being returned. What is the

I have a specific case where I am dealing with an array of 500 post IDs and I need to retrieve the first 100 posts. To achieve this, I implemented the following code:

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 contains 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;
        };

Issue

In some instances, when making an API call for individual post data, the response returns null. This results in a mix of posts and null values being rendered in the component, causing the application to crash. After manually refreshing the page, the API calls work fine without returning null responses.

For example, the fetch request for post with ID 28359987 may return null, but upon page refresh, a new API call retrieves the post successfully. However, the issue persists intermittently for other post IDs as well. How can this be resolved?

https://i.stack.imgur.com/8LQWD.png

Answer №1

If you encounter an API error that occurs for a specific request, rest assured that it is not a common occurrence. This CodeSandbox example here demonstrates that the API function always works reliably.

To remove any null values from your data, simply add .filter(Boolean) to your code. This will eliminate any unnecessary null results.

// Make sure to include () when using await
const storyList = (await Promise.all(promises)).filter(Boolean)
   

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When executing multiple promises in parallel, the function Promise.all() does not support the spread() method

I'm attempting to simultaneously run two promises using sequelize, and then display the results in a .ejs template. However, I keep encountering the following error: Promise.all(...).spread is not a function Below is my code snippet: var environme ...

What is the best way to create a dynamic pie chart in AngularJS using JSON data?

In my controller: When calling the web services, if the service is successful, then retrieve the data and push it into the corresponding arrays. for(var i = 0; i < $scope.reportRangeList.length; i++) { count++; if( ...

The Material UI textfield is not resetting after a change in state

Could someone help me figure out why my simple Text field is not clearing when a button is pressed? I am passing the state as a value to the textfield and changing the state, but the field remains filled... Check out the sandbox here export default functi ...

Is there a correlation between eliminating unnecessary imports and the size of the bundle as well as the speed of the build process

I am working on a Reactjs application built with Create React app, and I often encounter warnings during the startup and build process indicating that there are unused variables or imports in my Components. ./src/components/home/Header.js Line 10: & ...

React: Input field dynamically updates with each character typed

Currently, I am constructing a table using React and Material UI 5. However, I am facing an issue with the input field as it loses focus after each character is typed. Does anyone have suggestions on how to manage component re-rendering in this scenario? ...

Unusual layout in Next.js editor (VS Code)

My chosen formatter is prettier, but I'm encountering an issue with the way it handles simple JSX functions. Initially, my code looks like this: function HomePage() { return; <div> <h1>Hello Next.js</h1> <p> Welcome ...

What is the best way to apply a mask to a textbox to format the date as MM/yyyy using a mask

In my asp.net application, I have a TextBox for entering Credit card date (month & year only). I tried using the 'TextBox with masked edit extender' and set Mask="99/9999" with Mask Type="Date. However, it is not working as expected - it only wor ...

Why does my CSS attribute selector fail to update when the property's value changes?

Context: I'm working on a React-based web app that utilizes traditional CSS loaded through an import statement. In order to create a slider functionality, I have applied a CSS selector on the tab index attribute. Challenge: The issue I am facing is t ...

What is the best way to use jQuery to update the color of an SVG shape?

Hello everyone! I'm excited to be a part of this community and looking forward to contributing in the future. But first, I could really use some assistance with what seems like a simple task! My focus has always been on web design, particularly HTML ...

Activate a button with jQuery when a key is pressed

Currently, I have two buttons set up with jQuery: $('#prev').click(function() { // code for previous button }); $('#next').click(function() { // code for next button }); My goal now is to implement a .keypress() handler on the ...

When utilizing a Javascript event listener within ReactJS with NextJS, the dynamically imported module without server-side rendering fails to load

Hello everyone, I am new to ReactJS and NextJS and would really appreciate some advice on the issue below. Thank you in advance! Here is my current tech stack: Node v16.6.1 React v17.0.2 Next.js v10.0.4 I'm working on implementing a carousel and si ...

How can I change a PHP for loop to Javascript?

Can the following code be converted to JavaScript? for (let lift of liftDetails) { document.write('<option>'+ lift["LiftMakes"] +'</option>'); } ...

Utilizing the DirectusImage tag for a stylish background effect

I'm new to Directus and I need help styling a card with a background image from a Directus Image. Can anyone guide me on how to achieve this? Here's what I have tried: <Card style={{backgroundImage:"url({someColletion.image.id})" &g ...

The div swiftly clicks and moves beyond the screen with animated motion

Here is a code snippet that I am working with: $(document).ready(function(){ $(".subscriptions").click(function (){ if($(".pollSlider").css("margin-right") == "-200px"){ $('.pollSlider').animate({"margin-right": '+ ...

Is it possible for JavaScript within an <iframe> to access the parent DOM when

Is it possible for javascript in an iframe from a different domain to modify the parent's DOM? I need my iframed script to add new html elements to the parent page - any suggestions? Edit: One potential solution is using "Fragment ID Messaging" to co ...

How can we implement a functionality to close the fullscreen dialog from an external source, ensuring seamless user experience?

I passed a state as a prop from a functional component to a fullscreen dialog. How can I close the dialog after it is displayed by triggering onClose or onClick? const [openDialog, setOpenDialog] = React.useState(false); <MyDialog open={openDialog}/ ...

What could be the reason the server actions in nextjs 13 are not functioning correctly?

I am currently working on a project to retrieve data from mockapi.io, a mock API. However, I am encountering an issue where the fetched data is not displaying in the browser. There are no visible errors, and the browser window remains blank. Interestingly, ...

Adaptable images - Adjusting image size for various screen dimensions

Currently, my website is built using the framework . I am looking for a solution to make images resize based on different screen sizes, such as iPhones. Can anyone suggest the simplest way to achieve this? I have done some research online but there are t ...

Adjusting the rotation axis within the heart of the Three-react-fiber model

My model is rotating on the X axis, but the center of rotation is not aligned with the axis. The code for rotation is quite straightforward: model.current.rotation.x += 0.016; (axis and speed) However, I am struggling to define the actual axis of rotation ...

What are some solutions for resetting pagination icons to their default settings in material-table for React?

Hey there, I've been working on setting up a front-end display for a table using material-table in React. Everything has been going smoothly until I noticed some strange pagination icons instead of the usual arrows. Here's a screenshot for refere ...