i am making a simple todo app on react the app was working fine when i store my data in the predefined object. but now am i getting my data from a link (rest) using ajax , getting problem with this , path- pages/todo.js
import React from "react";
import Todo from "../components/Todo";
import * as TodoActions from "../actions/TodoActions.js";
import TodoStore from "../stores/TodoStore";
export default class Settings extends React.Component {
constructor(){
super();
this.getTodos=this.getTodos.bind(this);
this.state={
todos: TodoStore.getAll(),
};
console.log("STATE",this.state.todos);
}
componentDidMount(){
TodoStore.on("load",this.getTodos);
}
getTodos()
{
this.setState({
todos:TodoStore.getAll(),
});
}
reloadTodos(){
TodoActions.reloadTodos();
}
render() {
const {todos}=this.state;
const TodoComponents=todos.map((todo)=>{
return <Todo key={todo.id} {...todo}/>;
});
return (
<div>
<button onClick={this.reloadTodos.bind(this)}>Reload!!</button>
<h1>TODO.net</h1>
<ul>{TodoComponents}</ul>
</div>
)
}
}
path -stores/Todo
import {EventEmitter} from "events";
import * as $ from "jquery";
import dispatcher from "../Dispatcher";
class TodoStore extends EventEmitter
{
constructor(){
super()
this.todos=[];
}
createTodo(text)
{ const id=Date.now();
this.todos.push({
id,
text,
complete:false
});
this.emit("change");
}
getAll(){
$.ajax({
type: 'GET',
url: 'http://rest.learncode.academy/api/chitranks/todo',
success: function(data) {
console.log("here",data);
this.todos=data;
window.todos=this.todos;
}.bind(this),
error: function() {
alert('error GET connecting to REST');
}.bind(this)
});
return this.todos;
}
handleActions(action) {
switch(action.type){
case "CREATE_TODO":{
this.createTodo(action.text);
}
case "RECEIVED_TODOS":{
this.todos=action.todos;
this.emit("change");
}
}
}
}
const todoStore=new TodoStore;
dispatcher.register(todoStore.handleActions.bind(todoStore));
window.dispatcher=dispatcher;
export default todoStore;
when i type in console todos i can see the data, but it is not rendering (shows undefined)
and also in pages/todo.js file the object is undefined