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

Best way to update the state in one class component from the redux store?
Publish date: 2022-03-30 | Comments: 3

Tag: React js

React Redux : Connect is not called
Publish date: 2022-03-02 | Comments: 1

Tag: React js

Reload browser window using Reactjs?
Publish date: 2022-02-08 | Comments: 4

Tag: React js

React Component displaying a list of lines
Publish date: 2022-03-19 | Comments: 3

Tag: React js

[solved] Expected a conditional expression and instead saw an assignment
Publish date: 2021-11-29 | Comments: 0

Tag: React js

Export 'Switch' (imported as 'Switch') was not found in 'react-router-dom'
Publish date: 2022-04-02 | Comments: 2

Tag: React js

Module not found: Can't resolve 'swiper' in Reactjs [Solved]
Publish date: 2021-10-03 | Comments: 1

Tag: React js