Search code examples
reactjsgraphqlmaterial-uiapollo

Pass graphql variable to the Material UI component


I'm using React Typescript and have a Autocomplete Material UI component. I'm trying to get query suggestions into Autocomplete component.

My graphql queries looks like this:

Query Definition:

import gql from 'graphql-tag';
import {useQuery} from 'react-apollo';

const TODOS = gql`
  query todos($id: ID!) {
    todo(id: $id) {
      id
      name
    }
  }
`;

Query Initialization:

const { loading, error, data } = useQuery(TODOS, {
  variables: { id }
});

I want to create a autocomplete component which will take a numeric value from the textfield component and pass it on to the autocomplete material ui component?

My numeric component looks like this:

 <TextField
          id="filled-number"
          label="Number"
          type="number"
          InputLabelProps={{
            shrink: true,
          }}
          variant="filled"
        />

Autocomplete component:

<Autocomplete
                        id="combo-box-demo"
                        options={idx.name}
                        getOptionLabel={(option: {name: string}) => option.name}
                        style={{width: 300}}
                        renderInput={params => (
                          <TextField
                            {...params}
                            label="Combo box"
                            variant="outlined"
                          />

So it should set id from the number textfield component and then pass the query to the autocomplete component?


Solution

  • I don't know where idx.name comes from but it seems it is not an array while Autocomplete's property options requires an array type as a value.

    You need to pass data.todo into the Autocomplete prop options.

    Then you have to make your TextField component be controlled by state.

    Code example:

    const Component = () => {
      const [id, setId] = useState(%INITIAL_VALUE_IF_NEEDED%);
      
      const { data } = useQuery(DATA, {
        variables: { id },
      });
    
      const handleId = id => setId(id);
    
      return (
        <Fragment>
         <TextField {...params}
           label="Combo box"
           variant="outlined"
           onChange={handleChange}
         />
         <Autocomplete
           id="combo-box-demo"
           options={data?.todo || []}
           getOptionLabel={(option: {name: string}) => option.name}
           style={{width: 300}}
           renderInput={params => (
             <TextField
               {...params}
               label="Combo box"
               variant="outlined"
             />
           )}
        </Fragment>
      );
    }
    

    And then every time the id updates in the useQuery you will be able to see the options