user

Jo Micheal

4 Feb 2022

[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

4 Feb 2022

Best Answer

best answer
githubgithubgithub

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

Replies

Jo Micheal

4 Feb 2022

Thank you so much I will read about componentWillReceiveProps, it's very useful hook, it has done what I am looking for

© 2024 Copyrights reserved for web-brackets.com