skip to Main Content

I am trying to learn react by practising a simple problem.
I followed the below youtube tutorial
https://www.youtube.com/watch?v=AsvybgZTryo&list=PLKhlp2qtUcSZiWKJTi5-5r6IRdHhxP9ZU&index=17

but when I search for an item the item is not passing properly in the api call

https://dummyjson.com/users/search?q=${searchTerm}

can you let me know what is the issue, providing the codse snippet and stackblitz below

useEffect(() => {
    const fetchUsers = () => {
      if (searchTerm.trim() === '') {
        setSuggestions([]);
        return;
      }
      fetch('https://dummyjson.com/users/search?q=${searchTerm}')
        .then((res) => {
          res.json();
        })
        .then((data) => setSuggestions(data))
        .catch((err) => {
          console.log('error', err);
        });
    };
    fetchUsers();
  }, [searchTerm]);

2

Answers


  1. Problem is you are using ' instead of `
    So, your code should be

    fetch(`https://dummyjson.com/users/search?q=${searchTerm}`)
            .then((res) => {
              res.json();
            })
            .then((data) => setSuggestions(data))
            .catch((err) => {
              console.log('error', err);
            });
    

    Ref: Back-tick vs single quote in js

    Login or Signup to reply.
  2. Back-tick (`) instead of Single quote (‘)
    Copy the whole code here

    useEffect(() => {
        const fetchUsers = () => {
          if (searchTerm.trim() === '') {
            setSuggestions([]);
            return;
          }
          fetch(`https://dummyjson.com/users/search?q=${searchTerm}`)
            .then((res) => {
              res.json();
            })
            .then((data) => setSuggestions(data))
            .catch((err) => {
              console.log('error', err);
            });
        };
        fetchUsers();
      }, [searchTerm]);
    

    In JavaScript, backticks (`) are used to create template literals

    reference:
    https://www.dhiwise.com/post/unlock-the-power-of-js-backtick-template-literals-for-react

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search