Strategies for displaying error messages in case of zero search results

I am currently developing a note-taking application and facing an issue with displaying error messages. The error message is being shown even when there are no search results, which is not the intended behavior. Can someone help me identify what I am doing wrong?

Below is my code snippet along with the solutions I have attempted so far:


  const [notesList, setNotesList] = React.useState<string[]>([]);
  const [query, setQuery] = React.useState<string>("");

  const addNote = (): void => {
    setNotesList([...notesList, ""]);
  };

  const deleteNote = React.useCallback(
    (idx: number): void => {
      const newList = [...notesList];
      newList.splice(idx, 1);
      setNotesList(newList);
    },
    [notesList]
  );

  // More code here...

Answer №1

Only notes will be displayed in your condition, or the specified fallback text:

{filteredNotes && filteredNotes.length > 0 ? filteredNotes.map((note: string, idx: number) => (
          <Note
            onChange={updateNote}
            remove={deleteNote}
            idx={idx}
            text={note}
            key={idx}
          />
        )) : <Text>No results found</Text>}

In reference to what @kelly mentioned earlier, make sure to verify your notesList and skip rendering this section if you do not wish to display the fallback text.

There are numerous approaches to achieve this - creating a function to handle different scenarios for rendering would enhance readability. However, you can test the following solution to address your issue:

{notesList.length > 0 && 
  (filteredNotes && filteredNotes.length > 0 ? (
    filteredNotes.map((note: string, idx: number) => (
      <Note
        onChange={updateNote}
        remove={deleteNote}
        idx={idx}
        text={note}
        key={idx}
      />
    ))
  ) : (
    <Text>No results found</Text>
  ))}

If the notesList is empty, nothing will be rendered on the page.

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

Implementing automatic value setting for Material UI slider - a complete guide

I am working on developing a slider that can automatically update its displayed value at regular intervals. Similar to the playback timeline feature found on platforms like Spotify, Soundcloud, or YouTube. However, I still want the slider to be interactive ...

Running two different wdio.config.js files consecutively

Is it possible to run two wdio.config.js files with different configurations, one after another? Here is how the first configuration file is defined in the code: const { join } = require('path'); require('@babel/register') exports.co ...

What is the best way to create a circular graph using SVG in React Native?

I am attempting to create a circular graph using SVG in React Native. My goal is to include a stroke in the chart. How can I achieve this? I have already accomplished this. https://i.stack.imgur.com/hPIst.png This is the desired outcome. https://i.s ...

Instructions for sorting an array of objects by Firebase Timestamp

I am looking for a way to order my messages based on timestamp in Firebase v9. In earlier versions, I was able to do this but now I seem to be facing some difficulties. Here is the data structure set up on Firestore: const [messages, setMessages] = useSta ...

I'm encountering an error in TestCafe that says "TypeError: Cannot read properties of undefined (reading 'match')". Which specific segment of my code is causing this issue?

retrieveUrlFromEmailData(emailData:any){ const emailContent = emailData.email_text; const urlPattern = /(https?:\/\/[^\n]*)/; const foundUrl = emailContent.match(urlPattern)[0]; return foundUrl } ...

REACT performance impacted by slow array filtering

I have a custom listbox feature, where a div holds a vertical list of other div elements. There is also an input field for searching within the list. While it works fine with small data sets, it becomes extremely slow with large amounts of data. In additi ...

Tips for aligning a table at the center of a Material UI Paper component

I'm having trouble trying to center a fixed-sized table in the middle of the page using Paper component in Material-ui. I'm relatively new to Material-ui and not sure if I'm structuring it correctly. Can someone please help me with centering ...

Comparing the cost of memory and performance between using classes and interfaces

As I delve into writing TypeScript for my Angular project, one burning question arises — should I use an Interface or a Class to create my domain objects? My quest is to uncover solid data regarding the actual implications of opting for the Class route. ...

MUI full screen dialog with material-table

Issue: When I click a button on my material-table, it opens a full-screen dialog. However, after closing the dialog, I am unable to interact with any other elements on the screen. The dialog's wrapper container seems to be blocking the entire screen. ...

What is the best way to determine someone's age using their date of birth in a React

Looking for assistance with calculating a user's age from their date of birth on a registration form. I've tried various versions without success, can you provide some ideas that could be tailored to my project? Thank you. Here is the registratio ...

Angular mat-select is having difficulty displaying options correctly on mobile devices or devices with narrow widths

In my Angular project, I've encountered an issue with mat-select when viewing options on mobile or low-resolution screens. While the options are still displayed, the text is mysteriously missing. I attempted to set the max width of the mat-option, but ...

Encountering an error in Angular 8 where attempting to access an element in ngOnInit results in "Cannot read property 'focus' of null"

My html code in modal-login.component.html includes the following: <input placeholder="Password" id="password" type="password" formControlName="password" class="form-input" #loginFormPassword /> In m ...

Tips for avoiding the influence of the parent div's opacity on child divs within a Primeng Carousel

I'm struggling to find a solution to stop the "opacity" effect of the parent container from affecting the child containers. In my code, I want the opacity not to impact the buttons within the elements. I have tried using "radial-gradient" for multipl ...

What is the best way to add two values to the same index of an array?

I am currently working with React Leaflet and I am facing the challenge of passing some values to draw a Polyline. Here is an example of the value that needs to be passed: const polyline = [ [51.505, -0.09], [51.51, -0.1], [51.51, -100.12], ] This i ...

React-table fails to show newly updated data

I am facing an issue with my react-table where real-time notifications received from an event-source are not being reflected in the table after data refresh. https://i.stack.imgur.com/q4vLL.png The first screenshot shows the initial data retrieval from th ...

The system encountered an error when attempting to convert the data '19-10-2002' into a date format

I am trying to pass a date parameter in the format (dd-MM-yyyy) and then convert it into the format (yyyy-MM-dd) before sending it via API. Here is my code: convert(date:string){ date //is in the format(dd-MM-yyyy) date = formatDate(date , " ...

Exploring the world of design with React JS and MUI's diverse styling options

Exploring the various styling options offered by MUI From useTheme, styled, makeStyles to other methods - what sets them apart and how do they differ in use cases? We're looking for a comprehensive breakdown of their unique features, practical appli ...

Formik initialization does not prevent undefined errors in MUI textfield error and helpertext

It's perplexing why I keep encountering this issue - it has popped up a few times when attempting to utilize nested objects with Formik, React, and TypeScript. It appears that Formik is not compatible with data containing nested objects? https://i.st ...

Enhance Material UI BottomNavigationAction by adding a pseudo-element

Trying to enhance a selected item with an additional UI element using a pseudo-element. Specifically, looking to add a line above the menu item. https://i.stack.imgur.com/MZnmw.png The code I've implemented is not displaying the desired line: const ...

Preventing data loss in an Ionic array - encountering issues with using this.array.push

When attempting to use the storage get method to fill the array storedArr = [], I encounter the error message .push is not a function: storedArr = this.storage.get('stored') ? this.storage.get('stored').then((e) => {e}) : []; The c ...