1

I'm trying to create a simple search bar using react.js which will connect to my express.js back-end which will return the correct data from the database back to the front-end. But I haven't managed to understand how to send my custom research from my search bar in react to my back-end.

This is my Search component so far, it just creates a simple search bar which is supposed to send the query to the back-end:

mport React, { Component } from 'react';
import axios from 'axios';

export default class Search extends Component 
{
    constructor(){
        super()
        this.state = {
            query: '',
            result: [],
            filteredResult: []
        };
    }

    getData = () => {
        axios.get("/get-data").then(function(response){
            this.setState({
                result: response.data
            })
        });
    };

    handleInputChange = () => (
        this.setState({
            query: this.search.value
        }), () => {
            if (this.state.query) {
                this.getData()
            }
        }
    );

    componentDidMount(){
        this.getData();
    };

    render() {
        return (
            <form>
                <input placeholder="Search for..." ref={input => this.search = input} onChange={this.handleInputChange}/>
                <p>{this.state.query}</p>
            </form>
        );
    }
}

I can connect to the get-data rout, but I haven't managed to figure out how to send my search query to it. I've searched for quite a while and every example I've seen used a bunch of different API's from the web which isn't very helpful for my case.

So, how do I receive my search query inside of my back-end? Thanks!

1 Answer 1

4

the second param .get() of axios is config which can hold a params object for any query params to add to the request. The keys of that object is the query key and the value of the keys are the values of the query ?searchTerm=searchValue. So it might look something like

getData = () => {
        axios.get(
           "/get-data",
           {
               params: {searchTerm: this.state.query}
           }
       ).then(function(response){
            this.setState({
                result: response.data
            })
        });
    };
Sign up to request clarification or add additional context in comments.

1 Comment

Ohhhhhh, So simple yet so hard to find :] Thank you! Sadly when I try to enter some input the input is limited to 8 chars for some bizarre reasons but that's a problem for another time :]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.