user image

Jo Micheal
Published in : 2022-02-04

[solved] Reactjs is not updating the props

React js

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?

 

Comments

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

 componentWillReceiveProps(nextProps){ console.log(nextProps); this.applyFilters(nextProps.filter); if(nextProps.filters.country.length > 0){ this.props.updateCount(nextProps.filter); } }

& 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

Leave a comment

Join us

Join our community and get the chance to solve your code issues & share your opinion with us

Sign up Now

Related posts

[Solved] Cannot read properties of null (reading 'getBoundingClientRect')
Publish date: 2021-12-02 | Comments: 2

Tag: React js

How to use Datepick of Mui with Formik
Publish date: 2022-02-14 | Comments: 7

Tag: React js

React.Fragment. React.Fragment can only have key props and children
Publish date: 2022-08-06 | Comments: 2

Tag: React js

[solved] useEffect is repeating the request Reactjs
Publish date: 2022-04-07 | Comments: 2

Tag: React js