Terry Doll
Terry Doll

Reputation: 127

How to Set Initial Values to Formik using Axios with Typescript

I am new to using React, Formik, and Axios and not sure how to set the form's initial values from a database call. I have tried below code snippet, but have not been successful. I am unable to find any typescript examples online on how to do this.

async function getInitialValues() {
      try {
            const response = await axios.get('http://localhost:53132/api/test');
            //console.log(response);


            return {
                Division_Id: response.Divison_Id,
                Year: response.Year,
                Cost: response.Cost
            }

            //console.log(InitialValues);

            //return InitialValues;


          } catch (error) {
            console.error(error);
          }
    }


<Formik initialValues={getInitialValues()}...

Upvotes: 1

Views: 5197

Answers (2)

Gerard
Gerard

Reputation: 801

You'll want to make your network request on mount (using the "useEffect" hook in this example). Then save those values to state (using the useState hook here, but you can use Redux or whatever state management tool you're using).

function NewForm() {
  const [initialValues, setInitialValues] = useState();

  useEffect(() => {
    getInitialValues().then(res => setInitialValues(res);
  }, []);

  return initialValues ? 
    <Formik initialValues={initialValues}>content</Formik> :
    <span>loading...</span>;
}

Upvotes: 4

Muhammad Haseeb
Muhammad Haseeb

Reputation: 1341

Thats because you are missing the dependency in the useEffect. add an empty array as a dependency(second argument of useEffect) if you want to run only once, when page renders

   function NewForm() {
      const [initialValues, setInitialValues] = useState();

      useEffect(() => {
        getInitialValues().then(res => setInitialValues(res);
      }, []);

      return initialValues ? 
        <Formik initialValues={initialValues}>content</Formik> :
        <span>loading...</span>;
    }

Upvotes: 0

Related Questions