Dynamic search bar with a variable in a GraphQL query

841 views Asked by At

I have the following query working well back-end side:

{
  fuzzyArticleByTitle(searchString:"tiktok"){
    title
  }
}

The result is several article title matching with "tiktok" string.

I would like to code a dynamic search bar in front-end side with React using a variable for searchString.

I tried this:

import React, { Component} from 'react'
import { Query } from 'react-apollo'
import gql from 'graphql-tag'

const SearchQuery = gql`
query {
    fuzzyArticleByTitle($searchString: String){
        title
  }
}
`;

export default class Search extends Component {

constructor(props) {
    super(props)
    this.state = {
        search: ''
    }
}

updateSearch = (e) => {
    this.setState({
        search: e.target.value
    })
}

submitSearch = (e) => {
    e.preventDefault()
    console.log(this.state)
}

render() {

    const { search } = this.state;

    return (
        <form onSubmit={ this.submitSearch }>
            <input
                type='text'
                onChange={ this.updateSearch }
                value={ search }
                placeholder='Search'
            />
            <Query query={SearchQuery} skip={!search} variables={{query: search}}>
               {({loading, error, data}) => {
                    if (loading) return null;
                    if (error) throw err;
                   return <h1>{data.search.title}</h1>
                }}
            </Query>
        </form>
    )
}
}

It doesn't work. Where am I wrong ?

Maybe there is a better way to do this

1

There are 1 answers

0
Herku On

You have to declare the variable in the query header e.g.

query SearchArticles($searchString: String) {
    fuzzyArticleByTitle(searchString: $searchString){
        title
  }
}

and then use this specific variable name (you can chose any name in the declaration after the $) in Apollo:

<Query query={SearchQuery} skip={!search} variables={{searchString: search}}>
  {({loading, error, data}) => {
    if (loading) return null;
    if (error) throw err;
     return <h1>{data.search.title}</h1>
  }}
</Query>