I have two jsx files. TodoAPI.jsx has a function called getTodos() that uses axios to fetch data from a mongodb database and does so successfully as shown by testing. This function is usually called by certain lines in TodoApp.jsx, where apparently the entire code is executed before getTodos() even returns the array. Therefore, all the arrays that were supposed to be filled by getTodos() remain undefined. I made sure I am not wrong about this by using this setTimeout(function(){ console.log(TodoAPI.getTodos()); }, 3000); in TodoApp.jsx, where it actually printed the array.
How can I make sure getTodos() is finished before the rest of the code even starts? Or is there a better solution?
Here are the relevant parts of the code: TodoAPI.jsx:
var $ = require('jquery');
import axios from 'axios';
module.exports = {
setTodos: function (todos) {
if ($.isArray(todos)) {
localStorage.setItem('todos', JSON.stringify(todos));
return todos;
}
},
getTodos: function () {
let todos = [];
axios({
method: 'get',
//url:'https://nameless-island-69625.herokuapp.com/todos',
url: 'http://localhost:3000/todos',
headers:{
'x-auth': localStorage.getItem('x-auth')
}
}).then(function(response) {
todos = $.extend(true, [], response.data.todos);
console.log('successful response from todos');
}).then(() => {
console.log(todos);
return todos;
}).catch((e) => {
console.log('failed response from todos');
console.log(e);
});
// return [{name:'asd'},{name:'qwe'},{name:'fgd'},];
},
TodoApp.jsx:
var React = require('react');
var uuid = require('node-uuid');
var moment = require('moment');
const axios = require('axios');
var TodoList = require('TodoList');
var AddTodo = require('AddTodo');
var TodoSearch = require('TodoSearch');
var TodoAPI = require('TodoAPI');
var TodoApp = React.createClass({
getInitialState: function () {
return {
showCompleted: false,
searchText: '',
todos: TodoAPI.getTodos()
};
},
rest of the code can be found here but I am sure that the problem is in the code above.
getTodos: function () {