Search code examples
javascriptjqueryajaxreactjsrefluxjs

React reflux createStore $ajax trigger doesnt working


Hi I'm trying to get data updated with trigger but it dosn't working I'm new at react and reflux my part of code is:

import Reflux from 'reflux'
import $ from 'jquery'
import PeopleActions from  '../actions/PeopleActions.js'

let PeopleStore = Reflux.createStore({
    listenables: [PeopleActions],
    fetchPeople: function (){
        $.ajax({
            url: 'https://randomuser.me/api',
            dataType: 'json'
        })
        .done(function(peoples){
            let people = peoples.results
            this.trigger(people)
        })
    }
})

module.exports = PeopleStore

give me the next error:

PeopleStore.js?13fb:14 Uncaught TypeError: this.trigger is not a function
    at Object.eval (eval at <anonymous> (app.js:2617), <anonymous>:27:9)
    at fire (eval at <anonymous> (app.js:2623), <anonymous>:3317:31)
    at Object.fireWith [as resolveWith] (eval at <anonymous> (app.js:2623), <anonymous>:3447:7)
    at done (eval at <anonymous> (app.js:2623), <anonymous>:9272:14)
    at XMLHttpRequest.eval (eval at <anonymous> (app.js:2623), <anonymous>:9514:9)

Solution

  • What you have is a strange mix of the Store concepts and the Actions concepts. These are two related, but distinct, aspects of a flux flow. I would recommend finding a guide of reflux and paying close attention to the distinction between those concepts.

    Specifically, your function fetchPeople is an action, not a handler. The store would want to have a different method named onFetchPeople with a very different definition than what you've written.

    The error you have is completely expected, given that the concept of the "trigger" function only exists on actions, not stores. But beyond that, it doesn't make much sense to try to trigger an action from within itself.