grhmstwrt
grhmstwrt

Reputation: 341

ReactJS passing params to exported functions

I'm using an api to get post information, but i'm not trying to only request chunks of the data, to do this i'm just wanting to pass the range through the function - but i can't seem to do this, seems like a really simple request, can anyone help?

component requesting api information

constructor() {
        super();
        this.state = {
            posts: [],
            type: null,
            limit: 9,
            offset:0,
        }
        this.getPosts = this.getPosts.bind(this);
        this.toggleType = this.toggleType.bind(this);
    }
async componentDidMount(){
        var data = await api.newposts(this.state.offset,this.state.limit);
        this.setState({posts: data});
    }

and in my api request file;

export function newposts(limit,offset) {
    return new Promise(resolve => {

        var getLocalPosts = ls.get('api-request-posts');
        if(!getLocalPosts){
            axios.get(`${api}/posts?Publish=true&_sort=DatePublished:DESC`)
            .then(response => {
                resolve(response);
                ls.set('api-request-posts',JSON.stringify(response),ttl);
            }).catch(err => {
                resolve(err);
            })
        }
        else{
            var response = JSON.parse(getLocalPosts);
            var subset = response.data.slice(this.offset,this.limit);
            resolve(subset);
        }

    });

}

this file has loads of export function endpoints, all i want to do is pass through the variables to this export function, but nothing i provide seems to pull through to the endpoint...

where am i going wrong?

Upvotes: 1

Views: 929

Answers (1)

Ramesh Reddy
Ramesh Reddy

Reputation: 10662

Change the way you're accessing variables in your function this way:

export function newposts(limit,offset) {
    return new Promise(resolve => {

        var getLocalPosts = ls.get('api-request-posts');
        if(!getLocalPosts){
            axios.get(`${api}/posts?Publish=true&_sort=DatePublished:DESC`)
            .then(response => {
                resolve(response);
                ls.set('api-request-posts',JSON.stringify(response),ttl);
            }).catch(err => {
                resolve(err);
            })
        }
        else{
            var response = JSON.parse(getLocalPosts);
            var subset = response.data.slice(offset, limit);
            resolve(subset);
        }

    });

}

and also a good IDE with eslint extensions will help in preventing these mistakes because it'll mark the errors with a red line. One more thing is I would limit declaring variables with var, prefer let or const.

Upvotes: 1

Related Questions