Search code examples
reactjsnode-fetch

ReactJS - Fetch Route with Query Parameters


I'm facing an issue with my ReactJS setup where I am trying to retrieve query parameters in my url to append to the URL route that is being called in my fetch function. Is there a package I should be using to be able to achieve this? cheerio a ReactJS related package? Any way to do this without using react router or redux? I'm using node-fetch to make the call to my routes.

E.g. below would be 'http://localhost:3000/api?start_date=2017-11-05&end_date=2017-11-21'

class BlogFeedContainer extends React.Component{
    constructor(props, context) {
        super(props, context);
        this.state = this.context.data || window.__INITIAL_STATE__ || {blogs: []};
    }

    fetchList() {
        fetch('http://localhost:3000/api')
            .then(res => {
                return res.json();
            })  
            .then(data => {
                console.log("API Fetch Data Below");
                console.log(data);
                this.setState({ blogs: data.blog, user: data.user, csrf: data.csrfToken });
            }) 
            .catch(err => {
                console.log(err);
            });
    }

    componentDidMount() {
        this.fetchList();
    }

    render() {
        return (
            <div className="container">
                <BlogFeed {...this.state} />
            </div>
        )
    }
};

Solution

  • There's no need for any third party library. Just use the window.location object:

    window.location.search // => gives you query strings, starting with `?`