Antd add inital Values to dynamic form from firebase

Viewed 104

I want to take some data from firebase real time db and add them as the inital value for a dynamic form

              get(child(dbRef, `links/${dummy.prefix}/links/links`)).then((snapshot) => {
          
                if (snapshot.exists()) {
                  const dummy = snapshot.val();
                  setAlllinks(dummy)
                  for(var i in dummy){
                    setTheArray([...theArray, { "links" : [dummy[i]['first'], dummy[i]['last'] ]}]);
                  }
          
                } else {
                  console.log("No data available");
                }
              }).catch((error) => {
                console.error(error);
              });

This is the data that i get from firebase and add it to thearray

[
  {
    "first": "https://google.com",
    "last": "google"
  }
]

  const availablelinks = {

    links: theArray
  };
  const itemInputs = availablelinks.links.map((item) => {
    return {
      first: item.first,
      last: item.last,
    };
  });

for more details please see the git repohere

1 Answers

As long as your FormItem components have the name prop (I'm not sure if it's a required or optional prop in antd forms), you can set the initial values for the form items using initialValues prop of the Form component itself. For example, you can see this example form:

<Form
  name="basic"
  initialValues={{
    username: 'Hello',
    password: 'demo',
  }}>
  <Form.Item
    label="Username"
    name="username"
>
    <Input />
  </Form.Item>

  <Form.Item
    label="Password"
    name="password"
    >
    <Input.Password />
  </Form.Item>
</Form>;

Please make sure that the name prop of the field matches what you have in the initialValues prop. As far as, how to do it for a dynamic form is concerned, you can use the useState hook like this:

const [initialValues, setInitialValues] = useState();

and then when you get the data, you can update the state using setInitialValues and in the initialValues prop, you can use the initialValues={initialValues} for the Form component.

(You can check detailed implementation at this codesandbox fork: https://codesandbox.io/s/basic-usage-antd-4-23-1-forked-7i0rw0?file=/demo.js)

Related