0

I'm new to React and TypeScript. I have a textfield and a button using FluentUI. When a user types a value and clicks the button I need to pass the textfield input value to button onclick event and call the API with the search input. Here is my code:

export const OwnerPage: React.FunctionComponent = () => {

  const [TextFieldValue, setTextFieldValue] = React.useState('');
  const [owner, setOwner] = useState([]);
  const [err, setError] = useState({});

  const onClick = () => {    
    useEffect(() => {
      callMsGraph(TextFieldValue)
        .then(response => setOwner(response))
        .catch(err => setError(err));
    }, [])  
  }

  const onChangeTextFieldValue = React.useCallback(
    (event: React.FormEvent<HTMLInputElement | HTMLTextAreaElement>, newValue?: string) => {      
        setTextFieldValue(newValue || '');      
    },
    [],
  );

  const stackStyles: Partial<IStackStyles> = { root: { height: 44 } };
  return (
    <Page>
      <PageHeader/>
      <Text variant="xxLarge">Group Details</Text>
      <TextField
          ariaLabel={"GroupId"}       
          placeholder={"Group Id"}
          onChange={onChangeTextFieldValue}
          tabIndex={0}
        />
      <DefaultButton onClick={onClick}>{TextFieldValue}</DefaultButton>
    </Page>
  );
};

On running this, I see this error: React Hook "useEffect" is called in function "onClick" that is neither a React function component nor a custom React Hook function. React component names must start with an uppercase letter. React Hook names must start with the word "use". How do I fix that?

isherwood
  • 58,414
  • 16
  • 114
  • 157
user989988
  • 3,006
  • 7
  • 44
  • 91

1 Answers1

2

It is failing because you can't run useEffect hook on your onClick function, the useEffect hook is meant to be run on a functional component or a hook only, not inside your component inner functions, or the JSX code, you only have to remove the useEffect from the onClick and you'll be good to go.

  const onClick = () => {    
      callMsGraph(TextFieldValue)
        .then(response => setOwner(response))
        .catch(err => setError(err));
  }
jean182
  • 3,213
  • 2
  • 16
  • 27