Search code examples
javareactjsrestget

How to set parameters in a get request from reactJS


Maybe its a very newbie question for here but i spend a lot of time to see a good approach for doing this and i didn't find convenient answer. I am trying to make a simple call to a rest api and i want to pass a value with the GET request appended to the string. like url/foo where foo is the parameter. I have a query variable that i want to append to the end of the url string for the get request. Thank you in advance.

class About extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            products: [],
            filteredItems: [],
            user: {},
            query: '' <-- query variable to be appended to the end of the get request
        };

    }



    componentDidMount() {

        fetch(`'myurl/${this.state.query}'`) <-- i want to append the variable at the end of the string ??
            .then(res => res.json())
            .then((result) => {
                    console.log(result);
                    this.setState({
                        products: result,
                        filteredItems: result
                    });
                }
            )
    }

    queryChange = (evt) => {
        this.setState({query: evt.target.value}) <-- update the variable state from an event
    }





Solution

  • Get rid of the extra quotations (') in 'myurl/${this.state.query}'