user1730289
user1730289

Reputation: 377

Which is the preferred method, for React and TypeScript

Looking for an opinion on best practice going forward. We are using React with Typescript and starting a new project. Looking at previous projects I am seeing 2 different styles of programming along with most examples in here, on blogs and in documentation. I am wondering if there is a performance/memory or any difference between the 2 sample codes

Sample 1
export class CustomerService extends BaseService {
    public async GetBase(contactId: number): Promise<Contact> {
        try {
            let res = await fetch(this.BASEURL + 'Contacts/' + contactId.toString(),
                {
                    method: 'GET',
                    headers: {
                        'Authorization': `Bearer ${this._authentication.token.access_token}`
                    }
                });

                let results = await this.getBody(res);
                this.checkForErrors(res, results);
            let errors: ErrorList = this.checkForValidationErrors(res, results);
            if (errors != null) {
                return Promise.reject(errors);
            }
            return this._getContactEntity(results);
        }
        catch (err) {
            let errorList: ErrorList = this.buildErrorList(err, { 'key': 'Get Error', 'value': 'Failed to get contact', level: 0 });
            throw errorList;
        }
    }
}

//Sample 2
export const getSurvey = async (surveyPageId: number): Promise<Survey> => {
    const response = await getRequest('Survey', { contactId });
    const result = await response.json();
    const survey = new Survey(result[0]);
    return survey;
}

export const getRequest = async (endpoint: string, params?: URLParamType): Promise<Response> => {
    const endpointUrl = new URL(endpoint, document.location.href);
    if (params) {
        Object.keys(params).forEach(k => {
            endpointUrl.searchParams.append(k, params[k].toString());
        })
    }
    return fetcher(endpointUrl.toString(), {
        method: 'GET'
    })
}

I see some things that are different error handling and authentication in sample 1 but that could be fitted into sample 2 as well. Wondering how I should proceed on the new project.

Upvotes: 0

Views: 42

Answers (1)

Chris B.
Chris B.

Reputation: 5763

It looks like you're asking whether you should be using class components or functional components with hooks, in which case the answer is definitely the latter. Though class components are perfectly valid and will continue to be supported for a while, they are slowly being phased out in favor of functional components/hooks, so if you're starting a project from scratch there's no reason not to use them.

I'd recommend reading the documentation on hooks for a more in-depth explanation of why they were introduced and what advantages they offer over class-based components. Everything that can be accomplished with class components can be done with hooks (except error boundaries I believe), though the implementation will certainly be different.

Upvotes: 2

Related Questions