Home > database >  How do I set the initial value of a useState to a promise value
How do I set the initial value of a useState to a promise value

Time:06-29

I am making a textarea and I need the initial value to be the data gotten from the api fetch

It doesn't even make any sense, but I have no Idea of how else to do it. Help me out!

i have this

const [value, setValue] = useState(data?.content);

I'm fetching "data" from my backend api and it is undefined when the code runs initially because the useState is ran before the data is returned.

        <textarea
      className="noteText"
      type="text"
      value={value}
      onChange={(e) => {
        setValue(e.target.value);
      }}

CodePudding user response:

Your initial useState should be a value that can be rendered to the user or null, if you want to set the initial state use the useEffect hook setting the value using setValue.

CodePudding user response:

The initial value can't be the value from the Promise result if the Promise is constructed in the same component; the component must render before the API call starts (and finishes).

Either conditionally render the textarea only once the API call has finished

const [value, setValue] = useState();
useEffect(() => {
  someApiCall.then(setValue).catch(handleErrors);
}, []);

// ...

{
    value !== undefined && <textarea
        className="noteText"
        type="text"
        value={value}
        onChange={(e) => {
            setValue(e.target.value);
        }}
    ></textarea>
}

Or set the initial value to the empty string, where you still call setValue after the API call finishes. (The text the user types before the API call finishes will be lost - if the API call takes any reasonable amount of time, consider disabling the textarea until then with the readOnly prop)

const [value, setValue] = useState('');
useEffect(() => {
  someApiCall.then(setValue).catch(handleErrors);
}, []);

// ...

{
    <textarea
        className="noteText"
        type="text"
        value={value}
        onChange={(e) => {
            setValue(e.target.value);
        }}
    ></textarea>
}
  • Related