Problems in passing parameters to custom middleware - reactjs

Hi I am passing an id to the custom middleware I created in redux. here is my Dispatch function:
/** NPM Packages */
import React, { Component } from "react";
import { connect } from "react-redux";
import fetchCategory from "../../../actions/categoryAction";
import deleteCategory from "../../../actions/categoryDeleteAction";
/** Custom Packages */
import List from "../List";
//import API from "../../utils/api";
class Category extends Component {
constructor(props) {
super(props);
this.state = { categories: [], mesg: "", mesgType: "" };
this.onChange = this.onChange.bind(this);
}
/** Hook Call */
componentDidMount = async () => {
if (this.props.location.state)
this.setState({
mesg: this.props.location.state.mesg,
mesgType: this.props.location.state.mesgType
});
this.closeMesg();
this.props.fetchCategory();
};
/** Methods */
onChange = e => this.setState({ [e.target.name]: e.target.value });
onDelete = id => {
/*await API.delete("categories/" + id)
.then(res => {
const categories = this.state.categories.filter(el => el._id !== id);
this.setState({
categories: categories,
mesg: res.data.msg,
mesgType: "success"
});
})
.catch(err => console.log(err));
this.closeMesg();*/
this.props.deleteCategory(id);
};
closeMesg = () =>
setTimeout(
function() {
this.setState({ mesg: "", mesgType: "" });
}.bind(this),
30000
);
/** Rendering the Template */
render() {
const { mesg, mesgType } = this.state;
return (
<>
{mesg ? (
<div
className={"alert alert-" + mesgType + " text-white mb-3"}
role="alert"
>
{mesg}
</div>
) : (
""
)}
<List
listData={this.props.categories}
listName="category"
_handleDelete={this.onDelete.bind(this)}
/>
</>
);
}
}
const matchStatestoProps = state => {
return { categories: state.categories };
};
const dispatchStatestoProps = dispatch => {
return {
fetchCategory: () => dispatch(fetchCategory),
deleteCategory: (id) =>dispatch(deleteCategory(id))
};
};
export default connect(matchStatestoProps,dispatchStatestoProps)(Category);
Here is action:
import API from "../pages/utils/api";
const deleteCategory = (id,dispatch) =>{
API.delete("categories/" + id)
.then(() => {
dispatch({type:'DELETE'})
})
.catch(err => console.log(err));
}
export default deleteCategory;
here is my reducer:
const initState = [];
const categoryReducer = (state = initState, { type, payload }) => {
switch (type) {
case "FETCH_CATEGORY":
return payload.data;
case "DELETE":
alert("Data Deleted");
default:
return state;
}
};
export default categoryReducer;
Now i am getting this error :
Error: Actions must be plain objects. Use custom middleware for async actions.
▶ 6 stack frames were collapsed.
deleteCategory
src/app/pages/isolated/category/Categories.js:92
89 | const dispatchStatestoProps = dispatch => {
90 | return {
91 | fetchCategory: () => dispatch(fetchCategory),
> 92 | deleteCategory: (id) =>dispatch(deleteCategory(id))
93 | };
94 | };
95 |
If possible could someone say where am I going wrong?
Or is there any other way to pass parameters to the custom middleware?

Use redux-thunk as a middleware to handle async operations in Actions. Actions must be return plain objects, which means, something like below,
{
type : "DELETE",
payload : data
}
But in the Delete action you return a Promise, so that's why it is saying Actions must be return only plain objects. To handle this situation you can use a middleware like reduxt-thunk.
https://www.npmjs.com/package/redux-thunk
Edit -
If you use the Redux-thunk, In the catch bloack of the deleteCategory, you didn't return any object. You just console.log() the error. return the err from catch block and see if you see any errors with your API call

You can refer my react project
class Category extends Component {
constructor(props) {
super(props);
this.state = { categories: [], mesg: "", mesgType: "" };
this.onChange = this.onChange.bind(this);
}
/** Hook Call */
componentDidMount = async () => {
if (this.props.location.state)
this.setState({
mesg: this.props.location.state.mesg,
mesgType: this.props.location.state.mesgType
});
this.closeMesg();
this.props.dispatch(fetchCategory()); // we have to dispatch our action like
};
/** Methods */
onChange = e => this.setState({ [e.target.name]: e.target.value });
onDelete = id => {
this.props.dispatch(deleteCategory(id));
};
closeMesg = () =>
setTimeout(
function() {
this.setState({ mesg: "", mesgType: "" });
}.bind(this),
30000
);
/** Rendering the Template */
render() {
const { mesg, mesgType } = this.state;
return (
<>
{mesg ? (
<div
className={"alert alert-" + mesgType + " text-white mb-3"}
role="alert"
>
{mesg}
</div>
) : (
""
)}
<List
listData={this.props.categories}
listName="category"
_handleDelete={this.onDelete.bind(this)}
/>
</>
);
}
}
const matchStatestoProps = state => {
return { categories: state.categories };
};
export default connect(matchStatestoProps)(Category);
In your deleteCategory : you can access dispatch like
const deleteCategory = (id) => async (dispatch) =>{
await API.delete("categories/" + id)
.then(() => {
dispatch({type:'DELETE'})
})
.catch(err => console.log(err));
}
export default deleteCategory;

Related

PATCH request seems like a step behind

Hey folks really hope someone can help me here. I'm successfully updating my object in my mongo cluster, it updates but it does not render that update straight away to the browser. It will only update after a reload or when I run my update function again, it doesn't fetch that update straight away and I can't understand why. Does anyone have any suggestions?
I'm using context and reducer.
PlantDetails
import { usePlantsContext } from "../hooks/usePlantsContext";
import formatDistanceToNow from "date-fns/formatDistanceToNow";
import { useState } from "react";
import CalendarComponent from "./CalendarComponent";
const PlantDetails = ({ plant }) => {
const [watered, setWatered] = useState(false)
const [newWaterDate, setNewWaterDate] = useState("")
const { dispatch } = usePlantsContext();
const handleClick = async () => {
const response = await fetch("/api/plants/" + plant._id, {
method: "DELETE",
});
const json = await response.json();
if (response.ok) {
dispatch({ type: "DELETE_PLANT", payload: json });
}
};
const updatePlant = async (e) => {
e.preventDefault()
plant.nextWaterDate = newWaterDate
const response = await fetch("api/plants/" + plant._id, {
method: "PATCH",
body: JSON.stringify(plant),
headers: {
'Content-Type': 'application/json'
}
})
const json = await response.json()
if(response.ok) {
dispatch({ type: "UPDATE_PLANT", payload: json })
}
console.log('updated')
setWatered(false)
}
return (
<div className="plant-details">
<h4>{plant.plantName}</h4>
<p>{plant.quickInfo}</p>
<p>
{formatDistanceToNow(new Date(plant.createdAt), { addSuffix: true })}
</p>
<span onClick={handleClick}>delete</span>
<div>
<p>next water date: {plant.nextWaterDate}</p>
<input onChange={(e) => setNewWaterDate(e.target.value)}/>
<button onClick={updatePlant}>update</button>
<input value={watered} type="checkbox" id="toWater" onChange={() => setWatered(true)}/>
<label for="toWater">watered</label>
{watered && <CalendarComponent updatePlant={updatePlant} setNextWaterDate={setNewWaterDate}/>}
</div>
</div>
);
};
export default PlantDetails;
Context which wraps my
import { createContext, useReducer } from 'react'
export const PlantsContext = createContext()
export const plantsReducer = (state, action) => {
switch(action.type) {
case 'SET_PLANTS':
return {
plants: action.payload
}
case 'CREATE_PLANT':
return {
plants: [action.payload, ...state.plants]
}
case 'DELETE_PLANT':
return {
plants: state.plants.filter((p) => p._id !== action.payload._id)
}
case 'UPDATE_PLANT':
return {
plants: state.plants.map((p) => p._id === action.payload._id ? action.payload : p )
}
default:
return state
}
}
export const PlantsContextProvider = ({ children }) => {
const [state, dispatch] = useReducer(plantsReducer, {
plants: null
})
return (
<PlantsContext.Provider value={{...state, dispatch}}>
{ children }
</PlantsContext.Provider>
)
}
My plantController (update)
const updatePlant = async (req, res) => {
const { id } = req.params
if(!mongoose.Types.ObjectId.isValid(id)) {
return res.status(404).json({ error: "No plant" })
}
const plant = await Plant.findByIdAndUpdate({ _id: id }, {
...req.body
})
if (!plant) {
return res.status(400).json({ error: "No plant" })
}
res.status(200)
.json(plant)
}
Home component
import { useEffect } from "react";
import PlantDetails from "../components/PlantDetails";
import PlantForm from "../components/PlantForm";
import CalendarComponent from "../components/CalendarComponent";
import { usePlantsContext } from "../hooks/usePlantsContext";
const Home = () => {
const { plants, dispatch } = usePlantsContext();
useEffect(() => {
const fetchPlants = async () => {
console.log("called");
// ONLY FOR DEVELOPMENT!
const response = await fetch("/api/plants");
const json = await response.json();
if (response.ok) {
dispatch({ type: "SET_PLANTS", payload: json });
}
};
fetchPlants();
}, [dispatch]);
return (
<div className="home">
<div className="plants">
{plants &&
plants.map((plant) => <PlantDetails key={plant._id} plant={plant} />)}
</div>
<PlantForm />
</div>
);
};
export default Home;
Any help would be greatly appreciated.
My patch requests were going through smoothly but my state would not update until I reloaded my page. It was not returning the document after the update was applied.
https://mongoosejs.com/docs/tutorials/findoneandupdate.html#:~:text=%3B%20//%2059-,You,-should%20set%20the

calling async code in useState throwing null of undefined error

I am pretty new to react and redux. I am trying to call get method API in useEffect hook but the function I am calling isn't getting invoked at all. the same function is invoked when I tried calling outside the useEffect and the state is also updated but I still got that error Cannot read property 'map' of null. so in both the cases, the common thing is getting the error and my code seems good to me. all other functions and states are working except this and I am not able to figure out what I am missing. any help very much is appreciated. thank you.
Orders.js
const orders = (props) => {
// getting the orders
useEffect(() => {
props.fetchOrders();
}, []);
let orders;
if(props.loading || props.error) {
orders = <Loading />
}
console.log(props)
orders = props.orders.map((order) => <Order
key={order.id}
ingredients={order.ingredients}
price={order.price}
customer={order.customerDetails}
/>);
return(
<div>
{orders}
</div>
)
}
const mapStateToProps = state => {
return {
orders: state.orders,
error: state.error,
loading: state.loading
}
}
const mapDispatchToProps = dispatch => {
return {
fetchOrders: () => dispatch(getOrders())
}
}
export default connect(mapStateToProps, mapDispatchToProps) (errorHandler(orders, axiosInstance));
action.js
// not invoking
const getOrders = () => {
return dispatch => {
axiosInstance.get('/orders.json').then(res => {
const ordersData = transformData(res);
dispatch(fetchOrders(ordersData));
}).catch(err => {
console.log(err)
})
}
}
const transformData = (response) => {
// simplified logic
const ordersData = [];
if(response.data) {
for (let key in response.data) {
ordersData.unshift({
...response.data[key],
id: key
})
}
}
return ordersData;
}
const fetchOrders = (ordersData) => {
return {
type: actionTypes.GET_ORDERS,
orders: ordersData
}
}
export { getOrders }
reducer.js
const reducer = (state = intialState, action) => {
switch (action.type) {
.
.
case actionType.GET_ORDERS:
return setOrders(state, action);
.
.
default:
return state;
}
}
const setOrders = (state, action) => {
return {
...state,
orders: action.orders.concat(),
error: false,
loading: false
}
}

React redux update input field with user text after data filled from API

I am learning react hence this could be primitive problem but after lot of effort and searching I could not get this to work. Any help really appreciated.
Requirement
I have a html form which is filed by API response after user clicking a button. After API response user should be able to change the filled data.
Problem
From redux i set the properties from api call. This information set to state which uses to render to input field. when user types the data in input filed i cannot seems to change the state without causing infinite loop or not updating state at all.
This is my current work
class Counter extends Component {
constructor(props) {
super(props);
this.state = {
title: 'Initial title'
}
}
componentDidUpdate(prevProps, prevState, snapshot) {
if (this.props.hasOwnProperty('todoInfo')) {
const {title} = this.props.todoInfo;
if (title !== prevState.title) {
this.setState({
title: title
});
}
}
}
handleChange = (event) => {
const {name, value} = event.target;
this.setState((prevState) => ({
...prevState,
title: value
}));
}
render() {
const {title} = this.state;
return (
<div>
<p>
<button onClick={() => this.props.fetchData()}> fetch data</button>
</p>
<p>
<input type="text" id="fname" name="fname" value={this.state.title}
onChange={this.handleChange}></input>
</p>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('map state to props ' + JSON.stringify(state));
return {
todoInfo: state.todoReducers.todoInfo
};
};
const mapDispatchToProps = (dispatch) => ({
fetchData: () =>
dispatch(fetchData())
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
actions
export const fetchData = () => {
return (dispatch) => {
axios.get('https://jsonplaceholder.typicode.com/todos/1')
.then(response => {
const todoInfo = response.data;
dispatch({
type: GET_TODO,
payload: todoInfo
})
})
.catch(error => {
const errorMsg = error.message;
console.log(errorMsg);
});
};
};
reducer
const todoReducers = (state = {}, action) =>{
switch (action.type) {
case GET_TODO:
console.log('here ' + JSON.stringify(action));
return {
...state,
todoInfo: action.payload
};
default:
return state;
}
}
export default todoReducers;
I want my input text field load data from API then update with any user input. If they click fetch data again then user inputs are replaced by API fetch data. how to do this ?
EDIT
Solution according to accepted answer can be found https://github.com/mayuraviraj/react-redux-my-test
If your plan is to use redux, then you are trying to use a centralised state, don't mix it with the local state. (although it depends on your use case really)
Instead of your current code, remove the componentDidUpdate
class Counter extends Component {
constructor(props) {
super(props);
}
handleChange = (event) => {
const {name, value} = event.target;
this.props.changeTitle(value);
}
render() {
const {title} = this.state;
return (
<div>
<p>
<button onClick={() => this.props.fetchData()}> fetch data</button>
</p>
<p>
<input type="text" id="fname" name="fname" value={this.state.todoInfo}
onChange={this.handleChange}></input>
</p>
</div>
);
}
}
const mapStateToProps = (state) => {
console.log('map state to props ' + JSON.stringify(state));
return {
todoInfo: state.todoReducers.todoInfo
};
};
const mapDispatchToProps = (dispatch) => ({
fetchData: () =>
dispatch(fetchData()),
changeTitle: () => dispatch(changeTitle())
});
export default connect(mapStateToProps, mapDispatchToProps)(Counter);
Create another action:
export const changeTitle = (value) => ({
type: CHANGE_TODO_INFO,
payload: value
});
};
Then handle it in your reducer:
const todoReducers = (state = {}, action) =>{
switch (action.type) {
case GET_TODO:
console.log('here ' + JSON.stringify(action));
return {
...state,
todoInfo: action.payload
};
case CHANGE_TODO_INFO:
return {
...state,
todoInfo: action.payload
};
default:
return state;
}
}
export default todoReducers;
Don't forget to create the CHANGE_TODO_INFO variable, you get the idea
update title from redux in handleChange.
This fix should help:
handleChange = (event) => {
const {name, value} = event.target;
this.setState((prevState) => ({
...prevState,
title: value
}));
changeTitle(value);
}
const mapDispatchToProps = (dispatch) => ({
fetchData: () => dispatch(fetchData()),
changeTitle: (value) => dispatch({ type: GET_TODO, payload: value }),
});

debounce async/await and update component state

I have question about debounce async function. Why my response is undefined? validatePrice is ajax call and I receive response from server and return it (it is defined for sure).
I would like to make ajax call after user stops writing and update state after I get reponse. Am I doing it right way?
handleTargetPriceDayChange = ({ target }) => {
const { value } = target;
this.setState(state => ({
selected: {
...state.selected,
Price: {
...state.selected.Price,
Day: parseInt(value)
}
}
}), () => this.doPriceValidation());
}
doPriceValidation = debounce(async () => {
const response = await this.props.validatePrice(this.state.selected);
console.log(response);
//this.setState({ selected: res.TOE });
}, 400);
actions.js
export function validatePrice(product) {
const actionUrl = new Localization().getURL(baseUrl, 'ValidateTargetPrice');
return function (dispatch) {
dispatch({ type: types.VALIDATE_TARGET_PRICE_REQUEST });
dispatch(showLoader());
return axios.post(actionUrl, { argModel: product }, { headers })
.then((res) => {
dispatch({ type: types.VALIDATE_TARGET_PRICE_REQUEST_FULFILLED, payload: res.data });
console.log(res.data); // here response is OK (defined)
return res;
})
.catch((err) => {
dispatch({ type: types.VALIDATE_TARGET_PRICE_REQUEST_REJECTED, payload: err.message });
})
.then((res) => {
dispatch(hideLoader());
return res.data;
});
};
}
Please find below the working code with lodash debounce function.
Also here is the codesandbox link to play with.
Some changes:-
1) I have defined validatePrice in same component instead of taking from prop.
2) Defined the debounce function in componentDidMount.
import React from "react";
import ReactDOM from "react-dom";
import _ from "lodash";
import "./styles.css";
class App extends React.Component {
state = {
selected: { Price: 10 }
};
componentDidMount() {
this.search = _.debounce(async () => {
const response = await this.validatePrice(this.state.selected);
console.log(response);
}, 2000);
}
handleTargetPriceDayChange = ({ target }) => {
const { value } = target;
console.log(value);
this.setState(
state => ({
selected: {
...state.selected,
Price: {
...state.selected.Price,
Day: parseInt(value)
}
}
}),
() => this.doPriceValidation()
);
};
doPriceValidation = () => {
this.search();
};
validatePrice = selected => {
return new Promise(resolve => resolve(`response sent ${selected}`));
};
render() {
return (
<div className="App">
<input type="text" onChange={this.handleTargetPriceDayChange} />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
Hope that helps!!!
You can use the throttle-debounce library to achieve your goal.
Import code in top
import { debounce } from 'throttle-debounce';
Define below code in constructor
// Here I have consider 'doPriceValidationFunc' is the async function
this.doPriceValidation = debounce(400, this.doPriceValidationFunc);
That's it.

How to cancel a fetch on componentWillUnmount

I think the title says it all. The yellow warning is displayed every time I unmount a component that is still fetching.
Console
Warning: Can't call setState (or forceUpdate) on an unmounted component. This is a no-op, but ... To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
componentDidMount(){
return fetch('LINK HERE')
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
})
.catch((error) =>{
console.error(error);
});
}
When you fire a Promise it might take a few seconds before it resolves and by that time user might have navigated to another place in your app. So when Promise resolves setState is executed on unmounted component and you get an error - just like in your case. This may also cause memory leaks.
That's why it is best to move some of your asynchronous logic out of components.
Otherwise, you will need to somehow cancel your Promise. Alternatively - as a last resort technique (it's an antipattern) - you can keep a variable to check whether the component is still mounted:
componentDidMount(){
this.mounted = true;
this.props.fetchData().then((response) => {
if(this.mounted) {
this.setState({ data: response })
}
})
}
componentWillUnmount(){
this.mounted = false;
}
I will stress that again - this is an antipattern but may be sufficient in your case (just like they did with Formik implementation).
A similar discussion on GitHub
EDIT:
This is probably how would I solve the same problem (having nothing but React) with Hooks:
OPTION A:
import React, { useState, useEffect } from "react";
export default function Page() {
const value = usePromise("https://something.com/api/");
return (
<p>{value ? value : "fetching data..."}</p>
);
}
function usePromise(url) {
const [value, setState] = useState(null);
useEffect(() => {
let isMounted = true; // track whether component is mounted
request.get(url)
.then(result => {
if (isMounted) {
setState(result);
}
});
return () => {
// clean up
isMounted = false;
};
}, []); // only on "didMount"
return value;
}
OPTION B: Alternatively with useRef which behaves like a static property of a class which means it doesn't make component rerender when it's value changes:
function usePromise2(url) {
const isMounted = React.useRef(true)
const [value, setState] = useState(null);
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
useEffect(() => {
request.get(url)
.then(result => {
if (isMounted.current) {
setState(result);
}
});
}, []);
return value;
}
// or extract it to custom hook:
function useIsMounted() {
const isMounted = React.useRef(true)
useEffect(() => {
return () => {
isMounted.current = false;
};
}, []);
return isMounted; // returning "isMounted.current" wouldn't work because we would return unmutable primitive
}
Example: https://codesandbox.io/s/86n1wq2z8
The friendly people at React recommend wrapping your fetch calls/promises in a cancelable promise. While there is no recommendation in that documentation to keep the code separate from the class or function with the fetch, this seems advisable because other classes and functions are likely to need this functionality, code duplication is an anti-pattern, and regardless the lingering code should be disposed of or canceled in componentWillUnmount(). As per React, you can call cancel() on the wrapped promise in componentWillUnmount to avoid setting state on an unmounted component.
The provided code would look something like these code snippets if we use React as a guide:
const makeCancelable = (promise) => {
let hasCanceled_ = false;
const wrappedPromise = new Promise((resolve, reject) => {
promise.then(
val => hasCanceled_ ? reject({isCanceled: true}) : resolve(val),
error => hasCanceled_ ? reject({isCanceled: true}) : reject(error)
);
});
return {
promise: wrappedPromise,
cancel() {
hasCanceled_ = true;
},
};
};
const cancelablePromise = makeCancelable(fetch('LINK HERE'));
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
componentDidMount(){
cancelablePromise.
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
dataSource: responseJson,
}, () => {
});
})
.catch((error) =>{
console.error(error);
});
}
componentWillUnmount() {
cancelablePromise.cancel();
}
---- EDIT ----
I have found the given answer may not be quite correct by following the issue on GitHub. Here is one version that I use which works for my purposes:
export const makeCancelableFunction = (fn) => {
let hasCanceled = false;
return {
promise: (val) => new Promise((resolve, reject) => {
if (hasCanceled) {
fn = null;
} else {
fn(val);
resolve(val);
}
}),
cancel() {
hasCanceled = true;
}
};
};
The idea was to help the garbage collector free up memory by making the function or whatever you use null.
You can use AbortController to cancel a fetch request.
See also: https://www.npmjs.com/package/abortcontroller-polyfill
class FetchComponent extends React.Component{
state = { todos: [] };
controller = new AbortController();
componentDidMount(){
fetch('https://jsonplaceholder.typicode.com/todos',{
signal: this.controller.signal
})
.then(res => res.json())
.then(todos => this.setState({ todos }))
.catch(e => alert(e.message));
}
componentWillUnmount(){
this.controller.abort();
}
render(){
return null;
}
}
class App extends React.Component{
state = { fetch: true };
componentDidMount(){
this.setState({ fetch: false });
}
render(){
return this.state.fetch && <FetchComponent/>
}
}
ReactDOM.render(<App/>, document.getElementById('root'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Since the post had been opened, an "abortable-fetch" has been added.
https://developers.google.com/web/updates/2017/09/abortable-fetch
(from the docs:)
The controller + signal manoeuvre
Meet the AbortController and AbortSignal:
const controller = new AbortController();
const signal = controller.signal;
The controller only has one method:
controller.abort();
When you do this, it notifies the signal:
signal.addEventListener('abort', () => {
// Logs true:
console.log(signal.aborted);
});
This API is provided by the DOM standard, and that's the entire API. It's deliberately generic so it can be used by other web standards and JavaScript libraries.
for example, here's how you'd make a fetch timeout after 5 seconds:
const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 5000);
fetch(url, { signal }).then(response => {
return response.text();
}).then(text => {
console.log(text);
});
When I need to "cancel all subscriptions and asynchronous" I usually dispatch something to redux in componentWillUnmount to inform all other subscribers and send one more request about cancellation to server if necessary
The crux of this warning is that your component has a reference to it that is held by some outstanding callback/promise.
To avoid the antipattern of keeping your isMounted state around (which keeps your component alive) as was done in the second pattern, the react website suggests using an optional promise; however that code also appears to keep your object alive.
Instead, I've done it by using a closure with a nested bound function to setState.
Here's my constructor(typescript)…
constructor(props: any, context?: any) {
super(props, context);
let cancellable = {
// it's important that this is one level down, so we can drop the
// reference to the entire object by setting it to undefined.
setState: this.setState.bind(this)
};
this.componentDidMount = async () => {
let result = await fetch(…);
// ideally we'd like optional chaining
// cancellable.setState?.({ url: result || '' });
cancellable.setState && cancellable.setState({ url: result || '' });
}
this.componentWillUnmount = () => {
cancellable.setState = undefined; // drop all references.
}
}
I think if it is not necessary to inform server about cancellation - best approach is just to use async/await syntax (if it is available).
constructor(props){
super(props);
this.state = {
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
async componentDidMount() {
try {
const responseJson = await fetch('LINK HERE')
.then((response) => response.json());
this.setState({
isLoading: false,
dataSource: responseJson,
}
} catch {
console.error(error);
}
}
In addition to the cancellable promise hooks examples in the accepted solution, it can be handy to have a useAsyncCallback hook wrapping a request callback and returning a cancellable promise. The idea is the same, but with a hook working just like a regular useCallback. Here is an example of implementation:
function useAsyncCallback<T, U extends (...args: any[]) => Promise<T>>(callback: U, dependencies: any[]) {
const isMounted = useRef(true)
useEffect(() => {
return () => {
isMounted.current = false
}
}, [])
const cb = useCallback(callback, dependencies)
const cancellableCallback = useCallback(
(...args: any[]) =>
new Promise<T>((resolve, reject) => {
cb(...args).then(
value => (isMounted.current ? resolve(value) : reject({ isCanceled: true })),
error => (isMounted.current ? reject(error) : reject({ isCanceled: true }))
)
}),
[cb]
)
return cancellableCallback
}
one more alternative way is to wrap your async function in a wrapper that will handle the use case when the component unmounts
as we know function are also object in js so we can use them to update the closure values
const promesifiedFunction1 = (func) => {
return function promesify(...agrs){
let cancel = false;
promesify.abort = ()=>{
cancel = true;
}
return new Promise((resolve, reject)=>{
function callback(error, value){
if(cancel){
reject({cancel:true})
}
error ? reject(error) : resolve(value);
}
agrs.push(callback);
func.apply(this,agrs)
})
}
}
//here param func pass as callback should return a promise object
//example fetch browser API
//const fetchWithAbort = promesifiedFunction2(fetch)
//use it as fetchWithAbort('http://example.com/movies.json',{...options})
//later in componentWillUnmount fetchWithAbort.abort()
const promesifiedFunction2 = (func)=>{
return async function promesify(...agrs){
let cancel = false;
promesify.abort = ()=>{
cancel = true;
}
try {
const fulfilledValue = await func.apply(this,agrs);
if(cancel){
throw 'component un mounted'
}else{
return fulfilledValue;
}
}
catch (rejectedValue) {
return rejectedValue
}
}
}
then inside componentWillUnmount() simply call promesifiedFunction.abort()
this will update the cancel flag and run the reject function
Using CPromise package, you can cancel your promise chains, including nested ones. It supports AbortController and generators as a replacement for ECMA async functions. Using CPromise decorators, you can easily manage your async tasks, making them cancellable.
Decorators usage Live Demo :
import React from "react";
import { ReactComponent, timeout } from "c-promise2";
import cpFetch from "cp-fetch";
#ReactComponent
class TestComponent extends React.Component {
state = {
text: "fetching..."
};
#timeout(5000)
*componentDidMount() {
console.log("mounted");
const response = yield cpFetch(this.props.url);
this.setState({ text: `json: ${yield response.text()}` });
}
render() {
return <div>{this.state.text}</div>;
}
componentWillUnmount() {
console.log("unmounted");
}
}
All stages there are completely cancelable/abortable.
Here is an example of using it with React Live Demo
import React, { Component } from "react";
import {
CPromise,
CanceledError,
ReactComponent,
E_REASON_UNMOUNTED,
listen,
cancel
} from "c-promise2";
import cpAxios from "cp-axios";
#ReactComponent
class TestComponent extends Component {
state = {
text: ""
};
*componentDidMount(scope) {
console.log("mount");
scope.onCancel((err) => console.log(`Cancel: ${err}`));
yield CPromise.delay(3000);
}
#listen
*fetch() {
this.setState({ text: "fetching..." });
try {
const response = yield cpAxios(this.props.url).timeout(
this.props.timeout
);
this.setState({ text: JSON.stringify(response.data, null, 2) });
} catch (err) {
CanceledError.rethrow(err, E_REASON_UNMOUNTED);
this.setState({ text: err.toString() });
}
}
*componentWillUnmount() {
console.log("unmount");
}
render() {
return (
<div className="component">
<div className="caption">useAsyncEffect demo:</div>
<div>{this.state.text}</div>
<button
className="btn btn-success"
type="submit"
onClick={() => this.fetch(Math.round(Math.random() * 200))}
>
Fetch random character info
</button>
<button
className="btn btn-warning"
onClick={() => cancel.call(this, "oops!")}
>
Cancel request
</button>
</div>
);
}
}
Using Hooks and cancel method
import React, { useState } from "react";
import {
useAsyncEffect,
E_REASON_UNMOUNTED,
CanceledError
} from "use-async-effect2";
import cpAxios from "cp-axios";
export default function TestComponent(props) {
const [text, setText] = useState("");
const [id, setId] = useState(1);
const cancel = useAsyncEffect(
function* () {
setText("fetching...");
try {
const response = yield cpAxios(
`https://rickandmortyapi.com/api/character/${id}`
).timeout(props.timeout);
setText(JSON.stringify(response.data, null, 2));
} catch (err) {
CanceledError.rethrow(err, E_REASON_UNMOUNTED);
setText(err.toString());
}
},
[id]
);
return (
<div className="component">
<div className="caption">useAsyncEffect demo:</div>
<div>{text}</div>
<button
className="btn btn-success"
type="submit"
onClick={() => setId(Math.round(Math.random() * 200))}
>
Fetch random character info
</button>
<button className="btn btn-warning" onClick={cancel}>
Cancel request
</button>
</div>
);
}
Just four steps:
1.create instance of AbortController::const controller = new AbortController()
2.get signal:: const signal = controller.signal
3.pass signal to fetch parameter
4.controller abort anytime:: controller.abort();
const controller = new AbortController()
const signal = controller.signal
function beginFetching() {
var urlToFetch = "https://xyxabc.com/api/tt";
fetch(urlToFetch, {
method: 'get',
signal: signal,
})
.then(function(response) {
console.log('Fetch complete');
}).catch(function(err) {
console.error(` Err: ${err}`);
});
}
function abortFetching() {
controller.abort()
}
If you have a timeout clear them when component unmount.
useEffect(() => {
getReusableFlows(dispatch, selectedProject);
dispatch(fetchActionEvents());
const timer = setInterval(() => {
setRemaining(getRemainingTime());
}, 1000);
return () => {
clearInterval(timer);
};
}, []);
There are many great answers here and i decided to throw some in too. Creating your own version of useEffect to remove repetition is fairly simple:
import { useEffect } from 'react';
function useSafeEffect(fn, deps = null) {
useEffect(() => {
const state = { safe: true };
const cleanup = fn(state);
return () => {
state.safe = false;
cleanup?.();
};
}, deps);
}
Use it as a normal useEffect with state.safe being available for you in the callback that you pass:
useSafeEffect(({ safe }) => {
// some code
apiCall(args).then(result => {
if (!safe) return;
// updating the state
})
}, [dep1, dep2]);
This is a more general solution for async/await and promises.
I did this because my React callbacks were in between important async calls, so I couldn't cancel all the promises.
// TemporalFns.js
let storedFns = {};
const nothing = () => {};
export const temporalThen = (id, fn) => {
if(!storedFns[id])
storedFns[id] = {total:0}
let pos = storedFns[id].total++;
storedFns[id][pos] = fn;
return data => { const res = storedFns[id][pos](data); delete storedFns[id][pos]; return res; }
}
export const cleanTemporals = (id) => {
for(let i = 0; i<storedFns[id].total; i++) storedFns[id][i] = nothing;
}
Usage: (Obviously each instance should have different id)
const Test = ({id}) => {
const [data,setData] = useState('');
useEffect(() => {
someAsyncFunction().then(temporalThen(id, data => setData(data))
.then(otherImportantAsyncFunction).catch(...);
return () => { cleanTemporals(id); }
}, [])
return (<p id={id}>{data}</p>);
}
we can create a custom hook to wrap the fetch function like this:
//my-custom-fetch-hook.js
import {useEffect, useRef} from 'react'
function useFetch(){
const isMounted = useRef(true)
useEffect(() => {
isMounted.current = true //must set this in useEffect or your will get a error when the debugger refresh the page
return () => {isMounted.current = false}
}, [])
return (url, config) => {
return fetch(url, config).then((res) => {
if(!isMounted.current)
throw('component unmounted')
return res
})
}
}
export default useFetch
Then in our functional component:
import useFetch from './my-custom-fetch-hook.js'
function MyComponent(){
const fetch = useFetch()
...
fetch(<url>, <config>)
.then(res => res.json())
.then(json => { ...set your local state here})
.catch(err => {...do something})
}
I think I figured a way around it. The problem is not as much the fetching itself but the setState after the component is dismissed. So the solution was to set this.state.isMounted as false and then on componentWillMount change it to true, and in componentWillUnmount set to false again. Then just if(this.state.isMounted) the setState inside the fetch. Like so:
constructor(props){
super(props);
this.state = {
isMounted: false,
isLoading: true,
dataSource: [{
name: 'loading...',
id: 'loading',
}]
}
}
componentDidMount(){
this.setState({
isMounted: true,
})
return fetch('LINK HERE')
.then((response) => response.json())
.then((responseJson) => {
if(this.state.isMounted){
this.setState({
isLoading: false,
dataSource: responseJson,
}, function(){
});
}
})
.catch((error) =>{
console.error(error);
});
}
componentWillUnmount() {
this.setState({
isMounted: false,
})
}

Resources