score:1

Accepted answer

This is the usual structure of an async action to a reducer, but using typescript.

Basically you define the data types as interfaces on the top, those are just objects defining what kind of data you're expecting to pass through.

Then, you have the action and the reducer. The implementation of these is exactly the same as regular react-redux. However, you are implementing an async action (making an asynchronous call using fetch), so you also need to use redux-thunk and its type from typescript, AppThunkAction.

Therefore, you need to specify what 'thing' (type of data) every function is expecting to pass.

In case you need a particular data type (complex type), it's convenient to create an interface for it. Otherwise, you can repeat this complex type following the columns (:) of every object you want to assign it, but this is not recommended.

For example, if I'm expecting a object from an API call with id, name, hobbies and timestamp, an interface for that complex type would be:

export interface dataFromAPICall {
    id: number;
    name: string;
    hobbies?: string[];
    timestamp: number;
}

In this case, hobbies is optional (?) and it expects and array of strings ['football', 'sky', 'bodyboard surfing'].

In case of complex types on popular libraries, it is common that those types are already defined, such as AppThunkAction in redux, or ReactNode in React.

Hope this helps!


Related Query

More Query from same tag