Django Rest Framework + React + Reflux: Can't GET new objects

1k views Asked by At

I'm trying to post a new object via a React form using a Reflux action. That part is working fine. The object is posting as expected, however, when I try to GET that object programmatically, it doesn't seem to be accessible unless I log out, restart my local server, or sometimes even simply visit the api page manually.

I can't seem to get consistent behavior as to when I can get the object and when I can't. It does seem that viewing the api page and then returning to my app page has some kind of effect, but I'm at a loss as to why. Perhaps someone can shed a little light onto this for me.

One thing that's for sure is that the POST request is working properly, as the object is always there when I check for it manually.

Also, if you notice in the code below, I check to see what the last object on the api page is, and the console responds with what previously was the last item. So I'm able to access the api page programmatically, but the object I created is not there (though it is if I visit the page manually). Note, too, that refreshing produces the same results.

Any ideas where the issue could be or why this might happen?

Here's the action:

MainActions.getUserProfile.listen(function(user) {
  request.get('/api/page/').accept('application/json').end( (err, res) => {
    if (res.ok) {
        var profiles = res.body;
        var filteredData = profiles.filter(function (profile) {
            if (profile) {
                return profile.user === user
            }
            else {
                console.log('No Profile yet.')
            }
        });

        if (filteredData[0]) {
            var data = {
                user: filteredData[0].user,
                ...
            };
            ... // other actions
        } else {
            console.log(profiles[profiles.length - 1].user)
        }

    } else {
        console.log(res.text);
    }
  });
});
1

There are 1 answers

0
Matt Maresca On BEST ANSWER

The problem ended up being with the Cache-Control header of the response having a max-age=600. Changing that to max-age=0 solved the issue. In this situation, it doesn't make much sense to provide a cached response, so this I added this to my serializer's ViewSet:

def finalize_response(self, request, *args, **kwargs):
    response = super(MyApiViewSet, self).finalize_response(request, *args, **kwargs)
    response['Cache-Control'] = 'max-age=0'
    return response