-4

I need help with a React.js problem.

I am making a request with user input on a search bar I am using the hook useDebounce and when the user clears the input field after they got a result back. The array data becomes empty and the map function can not run on an empty array.

my question is

How do I check for empty array when the user clears out the input field.

App.jsx


// debounced query
  let {debouncedQuery} = useContext(DataContext)

useEffect(() => {
    // get the images of the breed that is choosen
    const loadByBreed = async (value: string) => {
      if (!debouncedQuery) return
      
      try {
        const response = await fetch(`https://dog.ceo/api/breed/${value}/images`)
        const data = await response.json()
        console.log(data)
        setImagesOfABreed(data.message)
      } catch (error) {
        const err = error as Error
        console.log(err.message)
      }
    }


    loadByBreed(debouncedQuery);

  }, [debouncedQuery])


{ debouncedQuery &&  imagesOfABreed?.length ? imagesOfABreed.map((data) => {
            return (
              <Card key={data} img={data} />
            )
          }) : <p>Nothing</p>}

neil
  • 353
  • 1
  • 8
  • 17
  • 1
    `map` can be run on an empty array, result is an empty array – Konrad Mar 20 '23 at 17:12
  • As pointed out `map` will work on an empty array, so you will likely find that's not your issue. If you show some code it might help so others can see what the issue is. – Keith Mar 20 '23 at 17:15
  • *"the map function can not run on an empty array"* - Sure it can, why would you assume otherwise? Is there some specific problem you are observing which is produced by some specific code? *"How do I check for empty array"* - `Array.isArray(myVar) && myVar.length === 0` ? – David Mar 20 '23 at 17:20
  • @David I have added some lines of code, please review. – neil Mar 20 '23 at 17:33
  • 1
    @neil: And in what way is your code not working as expected? – David Mar 20 '23 at 17:39
  • @David Please, how do I handle when the **user input** is not a breed of dog. – neil Mar 20 '23 at 19:49
  • @neil: You'd handle that in whatever way you *want* to handle that. You can show a default result, ignore the operation entirely, show an error, something else, etc. What specifically have you tried, how specifically does it not work as expected, and how specifically is that related to the question being asked above? Please clarify. – David Mar 20 '23 at 19:51
  • A user might input a word that is not a breed of dog e.g **Voyager**, this will cause the API to throw an error. How do I handle this error in `useEffect` @David – neil Mar 20 '23 at 19:54
  • 1
    @neil: If you're asking how to handle errors from `fetch`, your favorite search engine can [help get you started](https://stackoverflow.com/q/38235715/328193). You are encouraged to make an attempt. What you're asking also appears to have nothing to do with the original question, which itself was unclear. Comments are not a good place to ask entirely new questions. To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David Mar 20 '23 at 19:57
  • @David Please take a look at a question I formulated [here is the link](https://stackoverflow.com/questions/75794878/is-there-a-way-to-handle-wrong-user-input) – neil Mar 20 '23 at 20:11

1 Answers1

2

The problem actually originates at the formation of the fetch url for the API call. When the user empties the input field, the value becomes an empty string. So, the URL becomes something like this: https://dog.ceo/api/breed//images. Note the double-slashes in the URL because of the empty string in 'value'.

The API does provide a response in this case but the contents of the 'message' property in the response is a string. Note that both Array and String prototypes have the 'length' property. In this case, the condition while rendering the component's UI elements is satisfied and the code tries to run the map function on a string and that is where it fails.

One of the ways to fix it would be to add this snippet before the try-catch block:

if(!value) {
    setImagesOfABreed([]);
    return;
}
Phanisimha N R
  • 367
  • 1
  • 6
  • How do I handle when the **user input** is not a breed of dog – neil Mar 20 '23 at 19:48
  • You will need to check the value type of `imagesOfABreed` and if it is an array then render the Card component through map. – Phanisimha N R Mar 20 '23 at 20:07
  • please take a look [new question](https://stackoverflow.com/questions/75794878/is-there-a-way-to-handle-wrong-user-input) – neil Mar 20 '23 at 20:10
  • 1
    I have posted the answer there, however, here is something for you to think about: As @David rightly mentioned in the comment thread on this question, the community is glad to help, but only if you do your due diligence and homework properly. Next question onwards, ensure that you analyze the root cause of the problem you are facing, try things out first and post only when you have spent at least half a day hitting the wall. – Phanisimha N R Mar 20 '23 at 20:14