Jo Micheal
Published in : 2022-02-04
Hello everyone,
I have a problem in my React js application, when I have a parent & child components sometimes the props is not being updates & show the previous value of the props, How I can stop doing this?
example of the component which do this
import React from 'react';import { Box, Grid, Button, Checkbox, Typography, withStyles,} from '@material-ui/core';import BookmarkBorderIcon from '@material-ui/icons/BookmarkBorder';// import BookmarkIcon from '@material-ui/icons/Bookmark';import { withRouter } from 'react-router';const styles = (theme) => ({ root:{ },}); class Companies extends React.Component { state = { searchValue: '', sort: '', compare: [], alfaOrder: 'z', sortOptions:[ { name: 'Preferred supplier', value: 'Preferred supplier' } ] }; handleChange(optionId){ let arr = this.props.compareList; if (!arr.includes(optionId)) { arr.push(optionId); }else { arr = arr.filter(function(item) { return item !== optionId }) } console.log(arr); this.props.addCompare(arr); } render(){ console.log(this.props.filter); ... }}export default withStyles(styles)(withRouter(Companies));
Any idea How I can avoid this?
Join our community and get the chance to solve your code issues & share your opinion with us
Sign up Now
Mohamed Atef Date : 2022-02-04
Best answers
51
Best answers
51
This might happen because of the asynchronous of Reactjs functionality but If this happens when you, a method called componentWillReceiveProps you can use it to get the updated props in the class component, you can use it like
& You can compare it with the current state so if the state don't equal the nextProps you can setState
Good Luck
Jo Micheal Date : 2022-02-04
Thank you so much I will read about componentWillReceiveProps, it's very useful hook, it has done what I am looking for