skip to Main Content

I want to display default value for my Textfield. In this case I want to create the form when users will can update their profile but I need to display current data like name. Look at this simple example:

const ProfileSettings = () => {
  const [name, setName] = useState(10);
  const {
    register,
    formState: { errors },
  } = useForm({
    defaultValues: {
      name: name,
    },
  });
  useEffect(() => {
    axios.get("get-profile").then((data) => {
      setName(data.data.name);
    }, []);
  });

  return (
    <>
      <TextField
        id="name"
        defaultValue={name}
        label="name"
        type="string"
        variant="outlined"
        {...register("name")}
      />
    </>
  );
};

In this simple example Textfield display 10 (value from backend = 200). Value in useState id updated but it doesn’t updated value in TextField.

How can I update values in my form from backed?

2

Answers


  1. You need to pass the value to your TextField

     <TextField
        id="name"
        value={name} // here
        defaultValue={name}
        label="name"
        type="string"
        variant="outlined"
        {...register("name")}
      />
    

    See also the MUI docs for TextField

    Login or Signup to reply.
  2. can you try this..

    const ProfileSettings = () => {
      const [name, setName] = useState(null);
      const {
        register,
        formState: { errors },
      } = useForm({
        defaultValues: {
          name: name,
        },
      });
      useEffect(() => {
          getProfile();
        }, []);
      });
      
      const getProfile = async ()=>{
        axios.get("get-profile").then((data) => {
          setName(data.data.name);
        });
      }  
    
    
      return (
        <>
          <TextField
            id="name"
            defaultValue={name || ''}
            label="name"
            type="string"
            variant="outlined"
            {...register("name")}
          />
        </>
      );
    };
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search