简体   繁体   中英

Reset/clear fetched data on modal close

I have a modal that shows a d3 line chart on the views an article is getting. It is okay when you view the first graph. However, when viewing another article's data, the previous data remains which then overlaps with the new data. How do I reset the data on the modal every time I view a different article?

HTML:

       <tr>
         {% get_statistics "article_loads" article as load_stats %}
         {% get_statistics "clicks" article as click_stats %}
             <td>{{ article.title }}</td>
             <td data-toggle="modal" data-target="#loadHits" data-id="{{ load_stats.hash_key }}">{{ load_stats.total_hits }} hits</td>
             <td>{{ click_stats.total_hits }} hits</td>
             </tr>
         {% endfor %}

    {% for article in articles %}
    {% get_statistics "article_loads" article as load_stats %}
    <div id="loadHits" data-id="{{load_stats.hash_key}}" class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog"
         aria-labelledby="myLargeModalLabel" aria-hidden="true">
      <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <svg class="line" id="line">
                <svg class="lc"></svg>
            </svg>
        </div>
      </div>
    </div>
    {% endfor %}

Javascript:

$("#loadHits").on('shown.bs.modal', function(e){
const baseUrl = 'http://localhost:7000/search/api/content_date_aggs/?hash_key=';
let queryStr = $(e.relatedTarget).data('id'),
    fetchUrl = baseUrl + queryStr;
console.log(queryStr);
//Retrieve data from API
fetch(fetchUrl)
    .then(function (response) {
        return response.json();
    })
    .then(function (data) {
        var parsedData = formatData(data);
        createLineGraph(parsedData);

    })
    .catch((err) => {
        console.log(err);
    })
    .finally();
});

I have tried other solutions on resetting modal form data, however those were data found on HTML and my data is only passed within Javascript.

I want the modal to only show data of the current article instead of overlapping all datas of all the articles viewed.

Turns out the problem was with my createLineGraph function as it was generating and appending a new graph every time. Solved it by removing the previous graph before generating a new one by adding this line of code:

const lc = d3.select('.line')
    .attr("width", svgWidth)
    .attr("height", svgHeight)
    .style("margin-left", '6%');

d3.selectAll(".line > *").remove();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM