How do I use MUI (Material UI) and get form values

below is my code how do i get the value of all the form elements… if I use console.log() all the elements shoud me printed when a submit button is clicked how to do this… im using MUI

return(
<>
<form method="post" onSubmit={handleSubmit}>
        <Card sx={{ maxWidth: 800, minWidth:600 }}>
          <CardMedia sx={{ height: 250 }} image={banner} title="green iguana" />
          <CardContent>
            <Typography gutterBottom variant="h5" component="div" style={{marginBottom:"20px"}}>
              <SettingsIcon></SettingsIcon>Notification Settings
            </Typography><br />

            <TextField
            style={{width:"400px",marginBottom:"40px"}}
          required
          width="600"
          id="outlined-required"
          label="Whatsapp Number"
          defaultValue=""
          name='toWhatsappNumber'
        />
         <Typography variant="body2" color="text.secondary">
         Please Select the Hooks to send notifications
            </Typography>
            {data.length == 0 ? <p>Loading..</p> : group.map((gkey) => {
              return [<Typography gutterBottom variant="h6" marginTop="30px" component="div">{gkey.name}</Typography>,<hr />,
              data.map((wkey) => {
                if (gkey.id == wkey.group_id) {
                  // console.log(wkey.hook_name)
                  return [<div style={{marginLeft: "30px"}}><FormGroup>
                    <FormControlLabel
                      control={<Checkbox />} defaultChecked
                      label={wkey.hook_name}
                    />
                  </FormGroup></div>]
                }
              })]
            })}
          </CardContent>
          <CardActions style={{justifyContent: 'center'}}>
            <Button size="small" variant="contained" onClick={handleSubmit} >save</Button>
            {/* <Submit className="button">Save</Submit> */}
          </CardActions><br />
        </Card>
        </form>
</>
)

can any one please help me

Hey Rajeesh,

I would say part of the answer lies in how the handleSubmit function is behaving, and I do not see that code.

It might be better to create a minimal working repository and link to it; something we can spin up and test drive.

B

thanks for your quick response I’ll create a repo

1 Like

Can you put it in a repo I can clone, instead?

please use this link to clone Rajeesh / redwoodcommunityhelp · GitLab

below is a save button while clicking that I want to display all the values in console… after that I can use it to save it in db… i don’t know how to do this i’m new to react and node js

Rajeesh,

Note: for anyone else spinning this repo to help - I had to run prisma studio to create the “Group” and “Webhook” that the form expects to parse

Thanks for putting the repo up - I took a look at it. You mentioned not knowing React well - I am not the greatest either, especially with forms - but I will suggest some things.

First: I was able to alert the data using your code and by using <Form> and <TextAreaInput /> from the RW form library, and then logging the Submitted data.

This tells me the issue is with using the MUI form components. I can suggest perhaps two routes to try.

Route 1: Use an onChange function within each form element to update the state. This seems like a bad pattern, but may work. You would perhaps use one of these patterns to update the state object: reactjs - Handle an input with React hooks - Stack Overflow

I have not tested this pattern, and it seems very hacky. This may look something like:

<FormControlLabel
  control={<Checkbox onChange={handleChange} />}
  defaultChecked
  label={wkey.hook_name}
/>

Route 2: It seems more correct to use the form to collect the data, and then handle the data on submit. This gets you into the realm of A) either using RW native form components and helpers (like I did to test) or B.1) using MUI form components and wrapping them in a Controller or B.2) using formMethods and registering them.

B.1: Here is a link to Redwood docs using a Controller component.

B.2: Here is a link to how Alejandro uses formMethods and registers a MUI component.

Forms are something that even some of the best programmers around our community avoid. So, do not be discouraged by the difficulty. They can be difficult.

Rajeesh,

Something else that caught my eye - you are using webhooks to fetch your data, not using RW’s built in cells. This seems like an ‘anti-pattern’ within Redwood. Perhaps you have a good reason, as you have gone through the trouble to create the webhook on the api side and in the functions/basic.js file. So, I will not harp on it - but, Cells do the same thing and would make this process easier, and handle the loading/error/empty states for you.

Thank you so much for your kind reply I used react-hook-form and solved my problem… Thanks again

my current code looks like

  import { useForm } from 'react-hook-form'

  const {register, handleSubmit} = useForm([])
  const onSubmit = (data, e) => console.log(data, e);
  const onError = (errors, e) => console.log(errors, e);
<form onSubmit={handleSubmit(onSubmit, onError)}>
<TextField
            style={{width:"400px",marginBottom:"40px"}}
          required
          {...register('waNumber', { required: true })}
          width="600"
          id="outlined-required"
          label="Whatsapp Number"
          defaultValue=""
          name='toWhatsappNumber'
        />
<Button size="small" type="submit" variant="contained" onClick={handleSubmit} >save</Button>
</form>

:heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart: :heart:

I used cells but I faced some issue while retrieving in in the home page… but successfully I’m able to get the data in homepage by generating cells…

my issue is… i’m importing like

import Group from 'src/components/GroupsesCell'

and inside

return (
<Webhooks></Webhooks>
)

i can only use this i’m not able to parse the result from this tags and do further operations even if i’m returning the data in the cellspage like

export const Success = ({ groupses }) => {
  return (
    <>
      {groupses.map((item) => {
        // return <li key={item.id}>{JSON.stringify(item)}</li>
        return JSON.stringify(item)
      })}
    </>
  )
}

If there is any simple ways to fix this issue please guide me… Thanks in advance

Hey Rajeesh,

I am glad you have it working now :slight_smile: Honestly, getting the form going may be just fine for now and leave the cells for another day. If you have not worked through the tutorial, I recommend it. The first part gives a pretty good, and fairly quick, dive into how cells work. But, for now - the fetch pattern you built works and stopping to learn cells may not be a good use of time.

Perhaps I am wrong, but it seems like the way you are thinking about cells is that they act like your fetch/response function where they just return the requested data to the homepage to work with. This is not quite right. Instead of only fetching and returning the data, cells 1) fetch the data from the GraphQL API, where you then 2) parse & manipulate the data, and finally 3) return as a component to the parent.

If you want to use GraphQL to return data from the API like you are doing now, you could perhaps use the ApolloClient and query directly:

// In a react component...

client = useApolloClient()

client.query({
  query: gql`
    ...
  `
})

This may be somewhat equivalent to how you are fetching data now.

If you want to use cells I would suggest creating a “list” cell and, on the homepage, put the cell below where you have “Please Select the Hooks to send notifications.” Use the GraphQL query in the cell to structure and fetch the data in the JSON format. Then, in the Success component, parse and format the data into your “Group Names” and “Web Hook” lists. The cell would return the fully parsed div to the homepage as a component.

Again, I am not advocating that you change what you are doing right now. Your way works. But, there are other ways to fetch data with Redwood. The tutorial and docs go in-depth on cells, so they are worth reading over at some point. There are also discussions on the forums that touch on these concepts and patterns. One of RW’s goals is to provide conventions, like Cells, to help you skip common and tedious setup tasks like fetch/response functions. It makes it that much faster when all you do is run rw g cell <name>, structure your GraphQL query, and then can use the Empty, Loading, Failure, and Success states which are already mocked in the generated cell. Once you learn the pattern, your development workflow is that much faster.

Thank you so much for spending your time… For now i’m okay with the current method im using but sure I’ll learn and work with the cells concept later…

1 Like