skip to Main Content

How to write response from api to formik?
I have an api by which I receive data, this data is completely consistent with my form, how can I immediately write the entire response so as not to make many setFieldValue lines?

const form = useFormik({
        initialValues: {
          name: "",
          login: "",
          about: {
            age: "",
            rank: {
              silver: true,
              gold: false,
              global: false
            }
          }
        }
      }); // My initial form

  const {
    values,
    handleChange,
    setFieldValue,
  } = form;

useEffect(() => {
    if (!isEmpty(projectData)) {
      Object?.keys(projectData)?.map((item: any, idx: number) => {
        const key: any = Object.keys(item).at(-1);
        setFieldValue(key, item[key]);
      });
    }
  }, [projectData]); // Set response api 

2

Answers


  1. You have to set enableReinitialize to allow Formik to update the values upon changes.

    const form = useFormik({
        initialValues: ...,
        enableReinitialize: true //<-- Here
    });
    

    You can, also, directly set the values in a single go in your useEffect.

    useEffect(() => {
        if (projectData && .../*Other conditions*/) {
            form.setValues(projectData)
        }
    }, [projectData])
    
    Login or Signup to reply.
  2. If the shape of the data you’re receiving from the API matches the structure of your form, you can set the entire state at once using the setValues method.

    Make sure the data structure from your API response (projectData) matches the structure of your initialValues.

    Use the setValues method to update all the values at once.

    const form = useFormik({
      initialValues: {
        name: "",
        login: "",
        about: {
          age: "",
          rank: {
            silver: true,
            gold: false,
            global: false
          }
        }
      }
    });
    
    const { setValues } = form;
    
    useEffect(() => {
      if (projectData) {
        setValues(projectData);
      }
    }, [projectData]); // Set response from API
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search