React Error: Warning: React has detected a change in the order of Hooks called by Form

Viewed 58

I am learning the react js and following this tutorial but whenever I type something in the text field I am getting an error like following.

The error image:

I am using the material ui.

The code is as following:

const Form = () => {
  const [postData, setPostData] = useState({
    creator: "",
    title: "",
    message: "",
    tags: "",
    selectedFile: "",
  });

  const classes = useStyles();

  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventdefault();
    dispatch(createPost(postData));
  };
  return (
    <Paper className={classes.paper}>
      <form
        className={`${classes.root} ${classes.form}`}
        onSubmit={handleSubmit} >
        <Typography variant="h6">Creating a Memory</Typography>
        <TextField
          name="creator"
          label="Creator"
          value={postData.creator}
          onChange={(e) =>
            setPostData({ ...postData, creator: e.target.value })
          } />
        //... other fields
        <Button
          className={classes.buttonSubmit}
          type="submit"
          fullWidth >
          submit
        </Button>
      </form>
    </Paper>
  );
};

The app.js code where Form is getting called in:

function App() {
  const classes = useStyles();
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getPosts());
  }, [dispatch]);

  return (
    <Container maxWidth="lg">
      <AppBar className={classes.appBar} position="static" color="inherit">
        <Typography className={classes.heading} variant="h2" align="center">
          Memories
        </Typography>
        <img
          className={classes.image}
          src={memories}
          alt="memories"
        />
      </AppBar>
      <Grow in>
        <Container>
          <Grid
            spacing={3}
          >
            <Grid item xs={12} sm={7}>
              <Posts />
            </Grid>
            <Grid item xs={12} sm={4}>
              <Form />  //I am calling it here
            </Grid>
          </Grid>
        </Container>
      </Grow>
    </Container>
  );
}

The useState is in the correct order and I am not using the other hooks as well but somehow getting an error.

1 Answers

This problem happens when you call your hooks in loops, conditions, or nested functions. I think You are calling some kind of hook inside getPosts() function. This function is inside useEffect, so it will call conditionally, thus error.

Read this guide for a more detailed explanation.

Related