How to delete all old elements in functional component

248 Views Asked by At

I need to delete all old divs with h1 after fetching:

export default function SearchSong() {
    const [topSongs, setTopSongs] = useState([]);
    let inputEl = useRef(null);
    const fetchData = async () => {

upd. Here's fetch(returns correct data):

      let sTrack = inputEl.current.value;
        sTrack = sTrack.replace(/ /g,"+");
        try {
          const response = await fetch(
            `http://ws.audioscrobbler.com/2.0/?method=track.search&track=${sTrack}&api_key=a3c9fd095f275f4139c33345e78741ed&format=json`
          );
          const data = await response.json();
          setTopSongs(data);
        } catch (error) {
          console.log(error.message);
        }
      };
  
    return (
      <div>
<div className="inner-input">
        <div className="container">
            <h1 className="search" >Search for song:
            </h1>

There is input:

            <input ref={inputEl} size="50" type="text"/>
            <button class="btn btn-primary" onClick={fetchData} >Fetch</button>
        </div>
        </div>
        {topSongs?.results?.trackmatches?.track.length &&
          topSongs.results.trackmatches.track.map((datumn) => {
            return (
                <div key={datumn.name}>
                                  <h1 className='heading'>{datumn.name}</h1>
              </div>
            );
          })}
      </div>
    )
  }

I have tried useRef and delete parent element

1

There are 1 best solutions below

0
On BEST ANSWER

Fragments themselves are not rendered in the actual DOM tree. You usually use them to render 2 or more elements under a single root parent. So there's no use removing them after rendering.

You can, however, remove them from the map function and instead

return <h1 key={datum.name} className="heading">{datum.name}</h1>;

since you're returning a single root element anyway.


UPDATE

If you want to conditionally render depending on whether a statement is true or false:

{topSongs?.results?.trackmatches?.track.length ?
  topSongs.results.trackmatches.track.map((datumn) => {
    return (
      <div key={datumn.name}>
        <h1 className='heading'>{datumn.name}</h1>
      </div>
    );
}) : (
  <div className="inner-input">
    <div className="container">
      <h1 className="search" >Search for song:
      </h1>
      <input ref={inputEl} size="50" type="text"/>
      <button class="btn btn-primary" onClick={fetchData} >Fetch</button>
    </div>
  </div>
)}

The topSongs.results.trackmatches.track.map() will render when topSongs?.results?.trackmatches?.track.length > 0, otherwise the <div className="inner-input">..</div> will.