Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change the input initial value of controlled component in React

I have this input component

const FOO = props => {

  const [inputValue, setInputValue] = useState(
      props.editState ? props.initialValue : ""
  );

  const setSearchQuery = (value) => {
      setInputValue(value);
      props.onSearch(value);
  };

return (
  <input
    placeholder="Select ..."
    onChange={(e) => {
      setSearchQuery(e.target.value);
    }}
    value={inputValue}
  />
)}

I’m using it like this

const BAR = props => {
    const [fetchedData, setfetchedData] = useState({
        value : "" // to get rid of can't change controlled component from undefined error
    });
    const params = useParams();

    //request here to get fetchedData

return(
  <FOO
    onSearch={(value) => {
      searchSomethingHandler(value);
    }}
    initialValue={
      params.ID
      ? fetchedData.value
      : ""
    }
    editState={params.ID ? true : false}
  />
)}

I need to set the initial value of the fetched data into the input so the user could see the old value and edit it, if I pass the data (fetchedData) as props it works perfectly,
but if I get the data through API it wont set the value cause it’s empty at the first render,
how can I solve this please?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You’ll probably want to make use of the useEffect hook to run code when a value updates.

In FOO:

const FOO = props => {
  // ...

  useEffect(() => {
    // This hook runs when props.initialValue changes
    setInputValue(props.initialValue);
  }, [props.initialValue]);

  // ...
};

You can leave BAR the same as before, I think. Though, I would put the request to the API inside a useEffect hook with an empty dependency array so you’re not querying it on every render.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading