Sunday 11 July 2021

Using data models to handle API responses

I'd like to ask if it is beneficial to model the API response on the client. To be more specific:

First approach:

const [formData, setFormData] = useState(null);
...
useEffect(() => {
    const callback = async () => {
      try {
        const fetchData = await axios.get(...);
        setFormData(fetchData.data);
      } catch (e) {
        ...
      }
    };
    callback();
  }, []);


return(
<Form>
  <Input name="first name" value={formData.firstName}/>
  <Input name="last name" value={formData.lastName}/>
</Form>
)

Second approach:

const [formData, setFormData] = useState(new FormModel());
...
useEffect(() => {
    const callback = async () => {
      try {
        const fetchData = await axios.get(...);
        setFormData(...formData, fetchData.data);
      } catch (e) {
        ...
      }
    };
    callback();
  }, []);


return(
<Form>
  <Input name="first name" value={formData.firstName}/>
  <Input name="last name" value={formData.lastName}/>
</Form>
)

where FormModel has already been defined in another file like:

export class FormModel {
  firstName: string = undefined;
  lastName: string = undefined;
}

Is it the second approach more beneficial and why? Do we need to model the data fetched from the server? Wouldn't it be the same using an interface for formData in the first approach instead of implementing the second one?

P.S. The second approach might not make big difference from the first one. However, have seen many times that UI creates models for managing data fetched/sent from/to the server and wondering what are the real benefits we get.



from Using data models to handle API responses

No comments:

Post a Comment