Home > Software engineering >  Invalid hook call with select
Invalid hook call with select

Time:01-28

Problem is called in ProductSort(), reason is onChange.
I am getting 'invalid hook call' but I have no idea how to rewrite the code to skip this problem.
Maybe you have some ideas?

I will be appreciate, if you will send some links with examples of applications on GraphQL and React.

 function ShowCategories(){
    
       const { loading, error, data } = useQuery( gql`
        query{
             categories{ name }
           }
        `);
    
        if (error) return `Error! ${error}`;
    
        if(loading){
          return(<option>Loading...</option>);
        } else{
          return(  data.categories.map( (category, index) => {
            return(<option key={index} value={index}> {category.name} </option>)}) );
        }
    
       }
    
    function ProductSort() {
    
        return(
          <form id="plpChooseCategory">
            <div className="field">
              <select onChange={ (event) => ShowCategories({name: event.target.value})}>
                {ShowCategories()}
              </select>
            </div>
          </form>
        )

CodePudding user response:

React hooks can only be called from the body of React function components or custom React hooks. The code in your snippets if calling ShowCategories as if it were a regular function, which isn't how React components are used.

Move the useQuery logic into ProductSort and render the data into the options.

function ProductSort() {
  const { loading, error, data } = useQuery(gql`
    query{
      categories{ name }
    }
  `);

  const onChange = e => {
    const { value } = e.target;
    // do something with selected value
  };

  if (error) return `Error! ${error}`;

  return (
    <form id="plpChooseCategory">
      <div className="field">
        <select onChange={onChange}>
          {loading
            ? <option disabled value="">Loading...</option>
            : data.categories.map((category, index) => (
              <option key={index} value={index}>
                {category.name}
              </option>
            ))
          }
        </select>
      </div>
    </form>
  );
};
  •  Tags:  
  • Related