简体   繁体   English

如何使用Vanilla JavaScript将API调用中的数据存储到Firestore数据库中?

[英]How to store data from api call with vanilla javascript to firestore database?

I am bringing in data from an api call and outputting the data to html inside a template string using variables from the main.js file. 我正在通过api调用引入数据,并使用main.js文件中的变量将数据输出到模板字符串内的html中。 All of that works fine. 所有这些都很好。 The problem that has me blocked is I want to have an add to favorites button that a user can click and add the title to a favorites list. 我被阻止的问题是我想要一个“添加到收藏夹”按钮,用户可以单击该按钮并将标题添加到“收藏夹”列表中。 When I add the button inside the template literal the addEvenListener I have for the button is null and if I add the button to the index.html I cannot access the data from the api. 当我在模板文字中添加按钮时,该按钮具有的addEvenListener为null,如果将按钮添加到index.html,则无法从api访问数据。 I am trying to store the data first into firestore database after the user clicks the button. 我试图在用户单击按钮后首先将数据存储到Firestore数据库中。 Then output the data into a dropdown list. 然后将数据输出到下拉列表中。

I've added a collection to the firestore database and can display the data from the backend to the favorites list but I need to grab the data from the front end, store it on the back end, and display it in the favorites list. 我已经将集合添加到firestore数据库中,并且可以将后端的数据显示到收藏夹列表中,但是我需要从前端抓取数据,将其存储在后端,然后将其显示在收藏夹列表中。

 function getMovie(){
    let movieId = sessionStorage.getItem('movieId');
    // Make a request for a user with a given ID
    axios.get("https://api.themoviedb.org/3/movie/" + movieId + "? 
    api_key=redacted")
   .then(function (response) {
     console.log(response)
     let movie = response.data;
    //console.log(movie);
    let output = `
      <div class="dropdown">
        <button class="dropbtn" id="dropbtn">Favorites</button>
        <div id="myDropDown" class="dropdown-content"></div>
      </div>
  `;
  $('#movie').html(output);
  })
  .catch(function (error) {
    console.log(error);
  });     
}

addFavorite.addEventListener('submit', (e) => {
e.preventDefault();

firebase.firestore().collection('favorites').add({
   Title: addFavorite['movieid'].value

}).then(() => {
    //close 
    console.log(addFavorite)
})    
})

Not sure if I need to do another api call for this functionality or not. 不知道是否需要为此功能执行另一个api调用。 I did one api call to get a list of movies then another to get one movie. 我进行了一个api调用以获取电影列表,然后进行了另一个API来获取一部电影。 When the user goes to the one movie that is where I want the add favorite button. 当用户转到我要添加“收藏夹”按钮的一部电影时。 I hope someone knows how to lead me in the right direction. 我希望有人知道如何引导我朝正确的方向前进。 First time asking on Stackoverflow don't hurt me lol 第一次问Stackoverflow不会伤害我哈哈

i am taking simple ul list as example 我以简单的ul清单为例

<ul id="movie">
</ul>


<script>
    // DUMMY records
    const apiCallDataExample = [
        {
            id: 1,
            name: "A"
        },
        {
            id: 2,
            name: "B"
        },
        {
            id: 3,
            name: "C"
        }
    ];

    let movies = [];

    getMovie();

    function getMovie() {
        movies = apiCallDataExample; // You will call your API to get the data, and store it in upper scope 'movies' variable.
        let htmlContent = ''; // prepare your html content -> in your case it is droup down i guess.
        for (let movie of movies) {
            htmlContent += `
                <li>
                    <span> ${movie.name} </span>
                    <button onclick="addToFavourite(${movie.id})"> click me </button>
                </li>
            `

            // Attach click event or any listener to get selected movie id or any identifier
        }
        let elem = document.getElementById("movie").innerHTML = htmlContent;
    }


    /**
    *  click event will trigger and we can fetch selected movie by given identifier, in my case it is `id `field.
    */

    function addToFavourite(id) {
        let selected_movie = movies.find(movie => movie.id === id); // find your movie by id.
        console.log("selected movie is", selected_movie)
        // add your data into collection as per your defined property , my case { id, name}.

        /*

        // Your fire base function

        firebase.firestore().collection('favorites').add({
            id: selected_movie.id,
            name: selected_movie.name
        }).then(() => { })
        */
    }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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