1

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()}...

1
  • Are you getting any error? can you add more details please? Commented Jan 30, 2020 at 13:58

2 Answers 2

4

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>;
}
Sign up to request clarification or add additional context in comments.

1 Comment

I tried updating my code, but Stackoverflow is not allowing me to post the entire file. I have revised the code and it is available at below link. The app goes haywire and just keeps making calls to the service... github.com/tadstudios/CodeSandbox/blob/master/test
0

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>;
    }

1 Comment

Thanks for the help everyone! It finally clicked and have it working!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.