Home > Software engineering >  Change the input initial value of controlled component in React
Change the input initial value of controlled component in React

Time:08-01

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?

CodePudding user response:

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.

  • Related