Home > Mobile >  How to use an API response as initial value for input in ReactJS
How to use an API response as initial value for input in ReactJS

Time:04-05

Hello I am trying to make an input field that already has a preset value from an API response in ReactJS. I've tried using console.log(data[0].name) and it showed the value I was expecting and when I tried to show it in the frontend it also works fine. But when I try to show it as an initial value for my input field, it just gives me an empty input field. initialValue = {data[0].name}

Here's my app.js

import React, { useEffect, useState } from "react";
import { Form, Button, Input } from "antd";

function App() {
  const [data, setData] = useState([{}]);
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1/comments")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        console.log(data);
      });
  }, []);

  return (
    <div>
      {" "}
      <Form form={form} onFinish={onFinish}>
        <Form.Item
          className="Form-label"
          name="firstName"
          label="First Name"
          initialValue={data[0].name}
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter First Name"
          />
        </Form.Item>
        <Form.Item
          className="Form-label"
          name="middleName"
          label="Middle Name"
          initialValue=""
        >
          <Input
            maxLength={10}
            style={{ minWidth: 200, maxWidth: 500 }}
            placeholder="Enter Middle Name"
          />
        </Form.Item>
        <Form.Item>
          <div className="Btn-Primary-Create-Employee">
            <Button type="primary" htmlType="submit">
              Save
            </Button>
          </div>
        </Form.Item>
      </Form>
    </div>
  );
}

export default App;

Here's the object im fetching

[
  {
    "postId": 1,
    "id": 1,
    "name": "id labore ex et quam laborum",
    "email": "[email protected]",
    "body": "laudantium enim quasi est quidem magnam voluptate ipsam eos\ntempora quo necessitatibus\ndolor quam autem quasi\nreiciendis et nam sapiente accusantium"
  },
  {
    "postId": 1,
    "id": 2,
    "name": "quo vero reiciendis velit similique earum",
    "email": "[email protected]",
    "body": "est natus enim nihil est dolore omnis voluptatem numquam\net omnis occaecati quod ullam at\nvoluptatem error expedita pariatur\nnihil sint nostrum voluptatem reiciendis et"
  }
]

I've also made a codesandbox project to better visualize my issue

CodePudding user response:

setup a loading state and don't return unless loading is complete and that should fix it.

import React, { useEffect, useState } from "react";
import { Form, Button, Input } from "antd";

function App() {
  const [data, setData] = useState([{}]);
  const [loading, setLoading] = useState(true);
  const [form] = Form.useForm();
  const onFinish = (values) => {
    console.log("Received values of form: ", values);
  };

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/posts/1/comments")
      .then((res) => res.json())
      .then((data) => {
        setData(data);
        setLoading(false);
        console.log(data);
      })
      .catch((err) => {
        setLoading(false);
      });
  }, []);

  if (!loading) {
    return (
      <div>
        {" "}
        <Form form={form} onFinish={onFinish}>
          <Form.Item
            className="Form-label"
            name="firstName"
            initialValue={data.length ? data[0].name : "email"}
            label="First Name"
          >
            <Input
              maxLength={10}
              style={{ minWidth: 200, maxWidth: 500 }}
              placeholder="Enter First Name"
            />
          </Form.Item>
          <Form.Item
            className="Form-label"
            initialValue={data.length ? data[0].name : "email"}
            name="email"
            label="email"
          >
            <Input
              maxLength={10}
              style={{ minWidth: 200, maxWidth: 500 }}
              placeholder="Enter Middle Name"
            />
          </Form.Item>
          <Form.Item>
            <div className="Btn-Primary-Create-Employee">
              <Button type="primary" htmlType="submit">
                Save
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    );
  }
  return null;
}

export default App;

  • Related