skorphil / nextjs-form

Educational NextJs project to build a complex mobile-first form
https://www.chromatic.com/library?appId=65b2882ac1586a6b21cba0dd
MIT License
3 stars 0 forks source link

Error UI state if fetching error #72

Closed skorphil closed 6 months ago

skorphil commented 7 months ago

When fetching initial data for the form fails, the error notification must be displayed

Image

skorphil commented 6 months ago

Error handling playground: https://jsfiddle.net/skorphil/cbxu10kp/40/

skorphil commented 6 months ago

Not sure, but it looks like react-hook-form does not have a built-in mechanism for catching fetching errors. So error handling could be achieved via catching and setting state manually

defaultValues: async () => {
      try {
        await getLatestRecord();
      } catch (error) {
        console.log("defaultValues error:", error); // setState here
      }
    },
skorphil commented 6 months ago

Created a new react Component, which takes error message as a prop. It displayed based on errorState in RecordForm

https://github.com/skorphil/nextjs-form/assets/6762009/952ec7ae-6c3c-499e-b940-d722e7d7651d

skorphil commented 6 months ago

There is a bug - default values not receiving values after await

defaultValues: async () => {
      try {
        await getLatestRecord();
      } catch (error) {
        setErrorState(error.stack);
      }
    },

only this works:

defaultValues: async () => getLatestRecord();

so how to cath errors?

skorphil commented 6 months ago

Probably can be done with useEffect:

useEffect(() => {
  const fetchData = async () => {
    try {
      const data = await getLatestRecord();
      setLatestRecord(data);
    } catch (error) {
      setErrorState(error.stack);
    }
  };

  fetchData();
}, []);

But what the point in defaultValues compatible with promises?

skorphil commented 6 months ago

Ah, that is

There is a bug - default values not receiving values after await

defaultValues: async () => {
      try {
        await getLatestRecord();
      } catch (error) {
        setErrorState(error.stack);
      }
    },

only this works:

defaultValues: async () => getLatestRecord();

so how to cath errors?

ah, i just did not return the value - that was a problem

defaultValues: async () => {
      try {
        const initialValues = await getLatestRecord();
        return initialValues; // here
      } catch (error) {
        setErrorState(error.stack);
      }
    },