Answer the question
In order to leave comments, you need to log in
Return: React Component: Will there be a memory leak?
I want to catch all errors in the class that is responsible for interacting with the API, so as not to catch them in every component that calls methods of this class. Problem: The class is not related to React and Redux. Just a class with static methods. But the error handler should be able to dispatch actions to the store.
I think to implement something like this (I write the code on my knee, it is most likely not working, just an illustration of the idea):
const ErrorsHandler(error) => {
const mapDispatchToProps = dispatch => ({
newError: () => {
dispatch( { type: 'NEW_ERROR' } );
}
});
const DispatcherErrors = (props) => {
props.newError();
return null;
}
// Вернуть функцию-компонент, подключенный к стору
return connect(null, mapDispatchToProps)(DispatcherErrors)
}
// POST-запрос, ошибка передается в обработчик
API.post('auth', { login, pass })
.then(
res => res,
err => ErrorsHandler(err)
)
Answer the question
In order to leave comments, you need to log in
You are inventing a useless bicycle.
Option 1. If you are using redux-thunk :
export const handleError = error => ({ type: 'NEW_ERROR', payload: error });
export const doSomething = data => ({ type: 'DO_SOMETHING', payload: data });
import { apiCall } from './api';
import { handleError, doSomething } from './actionCreators';
export const asyncAction = () => dispatch => {
try {
const result = await apiCall();
dispatch(doSomething(result));
return result;
} catch (e) {
dispatch(hanldeError(e));
}
};
export const handleError = error => ({ type: 'NEW_ERROR', payload: error });
export const doSomething = data => ({ type: 'DO_SOMETHING', payload: data });
import { connect } from 'react-redux';
import { apiCall } from './api';
import { handleError, doSomething } from './actionCreators';
class ExampleComponent extends React.Component {
componentDidMount() {
const { dispatch } = this.props;
apiCall().then(
res => dispatch(doSomething(res)),
err => dispatch(handleError(err)),
);
}
render() { /* ... */ }
}
export default connect()(ExampleComponent);
import { connect } from 'react-redux';
import { apiCall } from './api';
import { handleError, doSomething } from './actionCreators';
class ExampleComponent extends React.Component {
componentDidMount() {
const { doSomething, handleError } = this.props;
apiCall().then(
res => doSomething(res),
err => handleError(err),
);
}
render() { /* ... */ }
}
mapDispatchToProps = {
handleError,
doSomething,
};
export default connect(null, mapDispatchToProps)(ExampleComponent);
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question