Home>

Is it possible to pass the response fetched from the DB with axios to another js file by return etc.?

I'm proceeding with the implementation with this procedure, but I've received the value in the 4th, but I don't know how to pass it to the js file.
1. Button is pressed in js file 1
2. axios get runs
3. Take DB information with laravel controller and return it with json
4. Receive it with axios and pass the information to js file 2.
5. Display the information in js file 2.

js file 1 (button action)

let clickSearch = document.getElementById ("searchAttendance");
if (clickSearch) {
  clickSearch.addEventListener ("click", function () {
    let searchData = {
      year: document.forms.searchTime.year.value,
      month: document.forms.searchTime.month.value,
    };
    indexAxios (searchData.year, searchData.month);
  });
}

axios (get)

export function indexAxios (year, month) {
    axios
        .get ("api/home", {params: {year: year, month: month}})
        .then (response =>{
            let year = response.config.params.year;
            let month = response.config.params.month;
            console.log (year)
            console.log (month)
            console.log (response.data)
            return response.data;
        })
        .catch (function (error) {
            return error;
        })
};


axios console.log results

js file 2

let axiosdata = indexAxios ();
console.log (axiosdata)


Anyway, it becomes unfifined.

  • Answer # 1

    Since axios performs asynchronous processing, it is necessary to wait for the arrival of json using async and await.

    let indexAxios = async (year.mounth) {
            let res = await axios
            .get ("api/home", {params: {year: year, month: month}})
            return res.data;
    }
    let main = async () =>{
            let axiosData = await index Axios (2020,11)
            console.log (axiosData)
    }

    Please adjust the data format returned from indexAxios accordingly.