I am using mui-datatable and based on the official example of this codesandbox, you can setState on the tableState. https://codesandbox.io/s/trusting-jackson-k6t7ot?file=/examples/on-table-init/index.js
handleTableInit = (action, tableState) => {
console.log("handleTableInit: ", tableState);
this.setState({ table: tableState });
};
handleTableChange = (action, tableState) => {
console.log("handleTableChange: ", tableState);
this.setState({ table: tableState });
};
I wanted to get the the tableState.displayData hence, I added this, however, this will result to an error that says:
Maximum update depth exceeded. This can happen when a component
repeatedly calls setState inside componentWillUpdate or
componentDidUpdate. React limits the number of nested updates to
prevent infinite loops.
const handleChange = (action, tableState) => {
console.log(tableState.displayData);
setDisplayedData(tableState.displayData);
};
const options = {
enableNestedDataAccess: ".",
print: false,
filterType: "multiselect",
selectableRows: "none",
downloadOptions: { filename: "Data.csv", separator: "," },
expandableRows: true,
onTableChange: handleChange,
onTableInit: handleTableChange,
I wanted to store the data of the tableState.displayData to the setDisplayedData. How can I fix this error?
I recreated this error on codesandbox: https://codesandbox.io/s/mui-datatable-reports-mqrbb3?file=/src/App.js:4130-4415
This is keep rendering because you have used setDisplayedData in the handleChange function. so whenever table change you update the state and it again changing the state. So it is going to an infinite loop.
you should put condition to check if data you are getting is different from the prev one or not. you can try isEqualwith & isEqual functions from lodash library to check if you new data is different from old or not.
const handleChange = (action, tableState) => {
console.log(tableState.displayData);
if(!isEqualwith(displayedData, tableState.displayData, isEqual)) {
setDisplayedData([...tableState.displayData]);}
};
Note: add lodash to you dependencies and import isEqualwith & isEqual functions.
Related
I'm trying to clean up my warnings, but im facing those dependency warnings.
This is an example, but a lot of useEffect() is facing a similar problem.
Im trying to laod my page calling my fetch api inside useCallback (got samething inside useEffect), but the filter param there is actually a redux state
useEffect(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(
indicationsAction.getIndications(config.page, config.rowsPerPage, config.order, {
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(beforeMonth),
dateEnd: dateFormat(today),
name: config.name,
indicatorName: config.indicatorName
}
})
)
} else {
router.push(`/${router.query.ambiente}`)
}
}, [env, config.status, config.order, dispatch, beforeMonth, config.indicatorName, config.name, config.page, config.rowsPerPage, router, today, user.login?.id, user.login.token])
Those filters has it value associated to an input, i do not want to re-fetch after change my config state, because i need to wait for the user fill all the filter fields, but i need to reload my page if my env change.
I thought about this solution, but it does not work
const filterParams = {
page: config.page,
rowsPerPage: config.rowsPerPage,
order: config.order,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(beforeMonth),
dateEnd: dateFormat(today),
name: config.name,
indicatorName: config.indicatorName
}
}
const loadPage = useCallback(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(
indicationsAction.getIndications({
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
}, filterParams)
)
} else {
router.push(`/${router.query.ambiente}`)
}
}, [dispatch, env, router, user.login?.id, user.login.token, filterParams])
useEffect(() => {
loadPage()
}, [loadPage])
Now I got the following warning:
The 'filterParams' object makes the dependencies of useCallback Hook (at line 112) change on every render. Move it inside the useCallback callback. Alternatively, wrap the initialization of 'filterParams' in its own useMemo() Hook.eslintreact-hooks/exhaustive-deps
if add filterParams to useMemo() dependencies samething will happend
// eslint-disable-next-line react-hooks/exhaustive-deps sounds not good ...
There's any solution for this ? I think that I have to change my form to useForm() to get the onChange values then after submit() i set my redux state... but i dont know yet
EDIT: In that case i did understand that we need differente states to control my input state and my request state, they cant be equals. If someone find another solution, i would appreciate (:
EDIT2: Solved by that way:
const [ filtersState ] = useState(
{
page: config.page,
rowsPerPage: config.rowsPerPage,
order: config.order,
data: {
environmentId: env[router.query.ambiente].envId,
loginId: user.login?.id,
selectorID: env.activeSelector?.selectorID,
token: user.login.token,
details: false,
filter: {
status: config.status,
dateInit: dateFormat(config.dateInit),
dateEnd: dateFormat(config.dateEnd),
name: config.name,
indicatorName: config.indicatorName
}
}
}
);
const handleLoadPage = useCallback(() => {
if (checkValidRoute(env.activeSelector.menu, "indicacoes")) {
dispatch(indicationsAction.getIndications({
...filtersState,
filters: {
...filtersState.filters,
selectorID: env.activeSelector?.selectorID,
}
}))
} else {
router.push(`/${router.query.ambiente}`)
}
}, [env.activeSelector, filtersState, dispatch, router]
)
useEffect(() => {
handleLoadPage()
}, [handleLoadPage])
Any other alternatives is appreciate
The thing here is, if you memoize something, it dependencies(if are in local scope) must be memoized too.
I recommend you read this amazing article about useMemo and useCallback hooks.
To solve your problem you need to wrap filterParams within useMemo hook. And if one of it dependencies are in local scope, for example the dateFormat function, you'll need to wrap it as well.
I have the following snippet of React that I can't get to work right. Essentially I'm displaying a spinner based on the state of this onChange call (due to the update sometimes taking 3-5 seconds). However, the first call to set state seems to go unnoticed (or as I'm researching being batched up) and therefore the state of loading is never updated. This is part of a toggle/switch a user can select infinite times on a page (if they desired obviously).
const [state, setState] = useState({ loading: false });
const onToggleChange = () => {
setState(prevState => {
return {
...prevState,
loading: true,
};
});
console.log("loading1: " + JSON.stringify(state));
// this takes a long time depending on the users actions
setFilterMode(!filterChecked);
setState(prevState => {
return {
...prevState,
loading: false,
};
});
console.log("loading2: " + JSON.stringify(state));
};
I've reviewed the current questions/answer (which is how I got as far as the above), but it still doesn't load correctly.
I am making an app with react native and firebase but I am having problem with error TypeError: undefined is not an object (evaluating 'this.state.desativado.push') when I click + button.
Complete code -> https://pastebin.com/a9HmB89G
Are you missing state = {desativados: []}; which has an 's' at the end?
Because from the code state = {desativado: ""};, desativado(without s at the end) is a string, there is no push method for it.
state = {itens: "", novositens: [], desativados: []}; // consolidate in one line to avoid overridden
this.setState({
desativados: this.state.desativados.concat(chave), // push to desativados instead of desativado
bagulho: this.state.novositens.concat(nome)
})
Better to get current state provided by setState
this.setState((state) => {
return {
desativados: state.desativados.concat(chave),
bagulho: state.novositens.concat(nome)
});
I have to create a text area which taken multiple links then I split() into array yeah Its working fine, but I want to set that array into my state in linkList: [] but when I click to button for submitting it gives me empty array as I initialize. but when I again press to submit button then it gives me my desired list, why? here are code and outputs
onSubmit = event => {
this.setState({ loading: true, host: undefined });
const { text, linkList } = this.state;
console.log(text);
const mList = text.split("\n").filter(String);
console.log(mList);
this.setState({
linkList: [...mList]
});
console.log(linkList);
event.preventDefault();
};
Output console (First Click)
youtube.com
google.com
facebook.com
------------------------------------------------------------
["youtube.com", "google.com", "facebook.com"]
------------------------------------------------------------
[]
Output Console (Second Click)
youtube.com
google.com
facebook.com
---------------------------------------------
["youtube.com", "google.com", "facebook.com"]
---------------------------------------------
["youtube.com", "google.com", "facebook.com"]
setState is asynchronous. That means it doesn't happen right away, but a very short time later instead. If you add a:
console.log(linkList)
to the top of your render method, you will see the items being appended just as you expect.
It probably is being appended, it's just not available until the next render.
From the documentation:
setState() does not always immediately update the component. It may batch or defer the update until later. This makes reading this.state right after calling setState() a potential pitfall. Instead, use componentDidUpdate or a setState callback (setState(updater, callback)), either of which are guaranteed to fire after the update has been applied.
The below code might help.
onSubmit = event => {
this.setState({ loading: true, host: undefined }, () => {
const { text, linkList } = this.state;
console.log(link);
const mList = text.split("\n").filter(String);
console.log(mList);
this.setState({
linkList: [...mList]
}, () => {
console.log(linkList);
event.preventDefault();
});
});
};
UPDATE: Yes for use case 1, if I extract search.value outside the useEffect and use it as a dependency it works.
But I have an updated Use case below
Use Case 2: I want to pass a searchHits Object to the server. The server in turn return it back to me with an updated value in response.
If I try using the searchHits Object I still get the infinite loop
state: {
visible: true,
loading: false,
search: {
value: “”,
searchHits: {....},
highlight: false,
}
}
let val = search.value
let hits = search.searchHits
useEffect( () => {
axios.post(`/search=${state.search.value}`, {hits: hits}).then( resp => {
…do something or ..do nothing
state.setState( prevState => {
return {
…prevState,
search: {... prevState.search, hits: resp.hit}
}
})
})
}, [val, hits])
Use Case 1: I want to search for a string and then highlight when I get results
e.g.
state: {
visible: true,
loading: false,
search: {
value: “”,
highlight: false,
}
}
useEffect( () => {
axios.get(`/search=${state.search.value}`).then( resp => {
…do something or ..do nothing
state.setState( prevState => {
return {
…prevState,
search: {... prevState.search, highlight: true}
}
})
})
}, [state.search])
In useEffect I make the API call using search.value.
eslint complains that there is a dependency on state.search , it does not recognize state.search.value. Even if you pass state.search.value it complains about state.search
Now if you pass state.search as dependecy it goes in an infinite loop because after the api call we are updating the highlights flag inside search.
Which will trigger another state update and a recursive loop.
One way to avoid this is to not have nested Objects in state or move the highlights flag outside search, but I am trying to not go that route give the sheer dependecies I have.
I would rather have an Object in state called search the way it is. Is there any way to better approach this.
If I want to keep my state Object as above how do I handle the infinite loop
Just a eslint stuff bug may be. You have retracted some code by saying //do something and have hidden he code. Are you sure that it doesn't have anything to do with search object?
Also, try to extract the variable out before useEffect().
const searchValue = state.search.value;
useEffect(()=>{// axios call here},[searchValue])
If your search value is an object, react does shallow comparison and it might not give desired result. Re-rendering on a set of object dependencies isn't ideal. Extract the variables.
React does shallow comparison of dependencies specified in useEffect
eg.,
const {searchParam1, searchParam2} = search.value;
useEffect(() => {
//logic goes here
}, [searchParam1, searchParam2]);
Additionally, you can add dev dependency for eslint-plugin-react-hooks, to identify common errors with hooks